home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Languages / Caml Light 0.7 / cl7refman.txt < prev    next >
Encoding:
Text File  |  1995-07-06  |  389.6 KB  |  11,128 lines  |  [TEXT/R*ch]

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28.                             The Caml Light system
  29.  
  30.  
  31.                                  release 0.7
  32.  
  33.  
  34.  
  35.                        Documentation and user's manual
  36.  
  37.  
  38.  
  39.                                  Xavier Leroy
  40.  
  41.  
  42.  
  43.                                  July 3, 1995
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.      Copyright oc 1995 Institut National de Recherche en Informatique et
  64.                                  Automatique
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77. Contents
  78.  
  79.  
  80.  
  81. I Getting started                                                            6
  82.  
  83. 1  Installation instructions                                                 7
  84.    1.1  The Unix version. . . . . . . . . . . . . . . . . . . . . . . . .    7
  85.    1.2  The Macintosh version . . . . . . . . . . . . . . . . . . . . . .    7
  86.    1.3  The PC version. . . . . . . . . . . . . . . . . . . . . . . . . .    8
  87.  
  88. II The Caml Light language reference manual                                 12
  89.  
  90. 2  The core Caml Light language                                             13
  91.    2.1  Lexical conventions . . . . . . . . . . . . . . . . . . . . . . .   14
  92.    2.2  Global names. . . . . . . . . . . . . . . . . . . . . . . . . . .   16
  93.    2.3  Values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .   17
  94.    2.4  Type expressions. . . . . . . . . . . . . . . . . . . . . . . . .   18
  95.    2.5  Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . .   19
  96.    2.6  Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . .   20
  97.    2.7  Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . .   22
  98.    2.8  Global definitions. . . . . . . . . . . . . . . . . . . . . . . .   29
  99.    2.9  Directives. . . . . . . . . . . . . . . . . . . . . . . . . . . .   31
  100.    2.10 Module implementations. . . . . . . . . . . . . . . . . . . . . .   31
  101.    2.11 Module interfaces . . . . . . . . . . . . . . . . . . . . . . . .   32
  102.  
  103. 3  Language extensions                                                      33
  104.    3.1  Streams, parsers, and printers. . . . . . . . . . . . . . . . . .   33
  105.    3.2  Guards. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .   34
  106.    3.3  Range patterns. . . . . . . . . . . . . . . . . . . . . . . . . .   34
  107.    3.4  Recursive definitions of values . . . . . . . . . . . . . . . . .   35
  108.    3.5  Local definitions using where . . . . . . . . . . . . . . . . . .   35
  109.    3.6  Mutable variant types . . . . . . . . . . . . . . . . . . . . . .   35
  110.    3.7  String access . . . . . . . . . . . . . . . . . . . . . . . . . .   36
  111.    3.8  Alternate syntax. . . . . . . . . . . . . . . . . . . . . . . . .   36
  112.    3.9  Infix symbols . . . . . . . . . . . . . . . . . . . . . . . . . .   36
  113.    3.10 Directives. . . . . . . . . . . . . . . . . . . . . . . . . . . .   37
  114.  
  115. III The Caml Light commands                                                 39
  116.  
  117. 4  Batch compilation (camlc)                                                40
  118.    4.1  Overview of the compiler. . . . . . . . . . . . . . . . . . . . .   40
  119.    4.2  Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . .   41
  120.    4.3  Modules and the file system . . . . . . . . . . . . . . . . . . .   44
  121.    4.4  Common errors . . . . . . . . . . . . . . . . . . . . . . . . . .   44
  122.  
  123. 5  The toplevel system (camllight)                                          48
  124.    5.1  Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . .   49
  125.    5.2  Toplevel control functions. . . . . . . . . . . . . . . . . . . .   51
  126.    5.3  The toplevel and the module system. . . . . . . . . . . . . . . .   53
  127.    5.4  Common errors . . . . . . . . . . . . . . . . . . . . . . . . . .   55
  128.  
  129.  
  130.                                       1
  131.  
  132.  
  133.                                                                              2
  134.  
  135.  
  136.    5.5  Building custom toplevel systems:  camlmktop. . . . . . . . . . .   55
  137.    5.6  Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . .   56
  138.  
  139. 6  The runtime system (camlrun)                                             57
  140.    6.1  Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . .   57
  141.    6.2  Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . .   57
  142.    6.3  Common errors . . . . . . . . . . . . . . . . . . . . . . . . . .   58
  143.  
  144. 7  The librarian (camllibr)                                                 60
  145.    7.1  Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . .   60
  146.    7.2  Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . .   60
  147.    7.3  Turning code into a library . . . . . . . . . . . . . . . . . . .   61
  148.  
  149. 8  Lexer and parser generators (camllex, camlyacc)                          63
  150.    8.1  Overview of camllex . . . . . . . . . . . . . . . . . . . . . . .   63
  151.    8.2  Syntax of lexer definitions . . . . . . . . . . . . . . . . . . .   64
  152.    8.3  Overview of camlyacc. . . . . . . . . . . . . . . . . . . . . . .   65
  153.    8.4  Syntax of grammar definitions . . . . . . . . . . . . . . . . . .   66
  154.    8.5  Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . .   68
  155.    8.6  A complete example. . . . . . . . . . . . . . . . . . . . . . . .   68
  156.  
  157. 9  The debugger (camldebug)                                                 70
  158.    9.1  Compiling for debugging . . . . . . . . . . . . . . . . . . . . .   70
  159.    9.2  Invocation. . . . . . . . . . . . . . . . . . . . . . . . . . . .   70
  160.    9.3  Commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . .   71
  161.    9.4  Executing a program . . . . . . . . . . . . . . . . . . . . . . .   72
  162.    9.5  Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . .   74
  163.    9.6  The call stack. . . . . . . . . . . . . . . . . . . . . . . . . .   75
  164.    9.7  Examining variable values . . . . . . . . . . . . . . . . . . . .   76
  165.    9.8  Controlling the debugger. . . . . . . . . . . . . . . . . . . . .   77
  166.    9.9  Miscellaneous commands. . . . . . . . . . . . . . . . . . . . . .   79
  167.  
  168. 10 Profiling (camlpro)                                                      80
  169.    10.1 Compiling for profiling . . . . . . . . . . . . . . . . . . . . .   80
  170.    10.2 Profiling an execution. . . . . . . . . . . . . . . . . . . . . .   81
  171.    10.3 Printing profiling information. . . . . . . . . . . . . . . . . .   81
  172.    10.4 Known bugs. . . . . . . . . . . . . . . . . . . . . . . . . . . .   81
  173.  
  174. 11 Using Caml Light under Emacs                                             82
  175.    11.1 Updating your .emacs. . . . . . . . . . . . . . . . . . . . . . .   82
  176.    11.2 The caml editing mode . . . . . . . . . . . . . . . . . . . . . .   82
  177.    11.3 Running the toplevel as an inferior process . . . . . . . . . . .   83
  178.    11.4 Running the debugger as an inferior process . . . . . . . . . . .   83
  179.  
  180. 12 Interfacing C with Caml Light                                            85
  181.    12.1 Overview and compilation information. . . . . . . . . . . . . . .   85
  182.    12.2 The value type. . . . . . . . . . . . . . . . . . . . . . . . . .   87
  183.    12.3 Representation of Caml Light data types . . . . . . . . . . . . .   88
  184.    12.4 Operations on values. . . . . . . . . . . . . . . . . . . . . . .   89
  185.    12.5 Living in harmony with the garbage collector. . . . . . . . . . .   91
  186.    12.6 A complete example. . . . . . . . . . . . . . . . . . . . . . . .   93
  187.  
  188. IV The Caml Light library                                                   96
  189.  
  190. 13 The core library                                                         97
  191.    13.1 bool:  boolean operations . . . . . . . . . . . . . . . . . . . .   97
  192.    13.2 builtin:  base types and constructors . . . . . . . . . . . . . .   98
  193.    13.3 char:  character operations . . . . . . . . . . . . . . . . . . .   98
  194.  
  195.  
  196.                                                                              3
  197.  
  198.  
  199.    13.4 eq:  generic comparisons  . . . . . . . . . . . . . . . . . . . .   99
  200.    13.5 exc:  exceptions  . . . . . . . . . . . . . . . . . . . . . . . .  100
  201.    13.6 fchar:  character operations, without sanity checks . . . . . . .  100
  202.    13.7 float:  operations on floating-point numbers  . . . . . . . . . .  101
  203.    13.8 fstring:  string operations, without sanity checks  . . . . . . .  102
  204.    13.9 fvect:  operations on vectors, without sanity checks  . . . . . .  102
  205.    13.10int:  operations on integers  . . . . . . . . . . . . . . . . . .  103
  206.    13.11io:  buffered input and output  . . . . . . . . . . . . . . . . .  105
  207.    13.12list:  operations on lists  . . . . . . . . . . . . . . . . . . .  110
  208.    13.13pair:  operations on pairs  . . . . . . . . . . . . . . . . . . .  112
  209.    13.14ref:  operations on references  . . . . . . . . . . . . . . . . .  113
  210.    13.15stream:  operations on streams  . . . . . . . . . . . . . . . . .  114
  211.    13.16string:  string operations  . . . . . . . . . . . . . . . . . . .  115
  212.    13.17vect:  operations on vectors  . . . . . . . . . . . . . . . . . .  116
  213.  
  214. 14 The standard library                                                    119
  215.    14.1 arg:  parsing of command line arguments . . . . . . . . . . . . .  119
  216.    14.2 baltree:  basic balanced binary trees . . . . . . . . . . . . . .  120
  217.    14.3 filename:  operations on file names . . . . . . . . . . . . . . .  121
  218.    14.4 format:  pretty printing  . . . . . . . . . . . . . . . . . . . .  122
  219.    14.5 gc:  memory management control and statistics . . . . . . . . . .  126
  220.    14.6 genlex:  a generic lexical analyzer . . . . . . . . . . . . . . .  128
  221.    14.7 hashtbl:  hash tables and hash functions  . . . . . . . . . . . .  129
  222.    14.8 lexing:  the run-time library for lexers generated by camllex . .  130
  223.    14.9 map:  association tables over ordered types . . . . . . . . . . .  131
  224.    14.10parsing:  the run-time library for parsers generated by camlyacc   132
  225.    14.11printexc:  a catch-all exception handler  . . . . . . . . . . . .  133
  226.    14.12printf:  formatting printing functions  . . . . . . . . . . . . .  133
  227.    14.13queue:  queues  . . . . . . . . . . . . . . . . . . . . . . . . .  134
  228.    14.14random:  pseudo-random number generator . . . . . . . . . . . . .  135
  229.    14.15set:  sets over ordered types . . . . . . . . . . . . . . . . . .  135
  230.    14.16sort:  sorting and merging lists  . . . . . . . . . . . . . . . .  137
  231.    14.17stack:  stacks  . . . . . . . . . . . . . . . . . . . . . . . . .  137
  232.    14.18sys:  system interface. . . . . . . . . . . . . . . . . . . . . .  138
  233.  
  234. 15 The graphics library                                                    141
  235.    15.1 graphics:  machine-independent graphics primitives  . . . . . . .  142
  236.  
  237. 16 The unix library:  Unix system calls                                    148
  238.    16.1 unix:  interface to the Unix system . . . . . . . . . . . . . . .  148
  239.  
  240. 17 The num library:  arbitrary-precision rational arithmetic               167
  241.    17.1 num:  operations on numbers . . . . . . . . . . . . . . . . . . .  167
  242.    17.2 arith_status:  flags that control rational arithmetic . . . . . .  170
  243.  
  244. 18 The str library:  regular expressions and string processing             171
  245.    18.1 str:  regular expressions and high-level string processing  . . .  171
  246.  
  247. V Appendix                                                                 175
  248.  
  249. 19 Further reading                                                         176
  250.    19.1 Programming in ML . . . . . . . . . . . . . . . . . . . . . . . .  176
  251.    19.2 Descriptions of ML dialects . . . . . . . . . . . . . . . . . . .  177
  252.    19.3 Implementing functional programming languages . . . . . . . . . .  178
  253.    19.4 Applications of ML. . . . . . . . . . . . . . . . . . . . . . . .  179
  254.  
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.  
  262.  
  263.  
  264.  
  265.  
  266. Foreword
  267.  
  268.  
  269.  
  270. This manual documents the release 0.7 of the Caml Light system.  It is
  271. organized as follows.
  272.  
  273.  -  Part I, ``Getting started'', explains how to install Caml Light on your
  274.     machine.
  275.  
  276.  -  Part II, ``The Caml Light language reference manual'', is the reference
  277.     description of the Caml Light language.
  278.  
  279.  -  Part IV, ``The Caml Light library'', describes the modules provided in
  280.     the standard library.
  281.  
  282.  -  Part III, ``The Caml Light commands'', documents the Caml Light compiler,
  283.     toplevel system, and programming utilities.
  284.  
  285.  -  Part V, ``Appendix'', contains a short bibliography, an index of all
  286.     identifiers defined in the standard library, and an index of Caml Light
  287.     keywords.
  288.  
  289.  
  290. Conventions
  291.  
  292. The Caml Light system comes in several versions:  for Unix machines, for
  293. Macintoshes, and for PCs.  The parts of this manual that are specific to one
  294. version are presented as shown below:
  295.  
  296. Unix: This is material specific to the Unix version.
  297.  
  298. Mac:  This is material specific to the Macintosh version.
  299.  
  300. PC:   This is material specific to the PC version.
  301.  
  302.  
  303. License
  304.  
  305.                                    c
  306. The Caml Light system is copyright o 1989, 1990, 1991, 1992, 1993, 1994, 1995
  307. Institut National de Recherche en Informatique et en Automatique (INRIA).
  308. INRIA holds all ownership rights to the Caml Light system.  See the file
  309. COPYRIGHT in the distribution for the copyright notice.
  310.   The Caml Light system can be freely copied, but not sold.  More precisely,
  311. INRIA grants any user of the Caml Light system the right to reproduce it,
  312. provided that the copies are distributed free of charge and under the
  313. conditions given in the COPYRIGHT file.  The present documentation is
  314. distributed under the same conditions.
  315.  
  316.  
  317.  
  318.  
  319.  
  320.  
  321.                                       4
  322.  
  323.  
  324.                                                                              5
  325.  
  326.  
  327. Availability by FTP
  328.  
  329. The complete Caml Light distribution resides on the machine ftp.inria.fr.  The
  330. distribution files can be transferred by anonymous FTP:
  331.  
  332.            Host:       ftp.inria.fr (Internet address 192.93.2.54)
  333.            Login name: anonymous
  334.            Password:   your e-mail address
  335.            Directory:  lang/caml-light
  336.            Files:      see the index in file README
  337.  
  338.  
  339.  
  340.  
  341.  
  342.  
  343.  
  344.  
  345.  
  346.  
  347.  
  348.  
  349.  
  350.  
  351.  
  352.  
  353.  
  354.  
  355.  
  356.  
  357.  
  358.  
  359.  
  360.  
  361.                                     Part I
  362.  
  363.  
  364.  
  365.                                Getting started
  366.  
  367.  
  368.  
  369.  
  370.  
  371.  
  372.  
  373.  
  374.  
  375.  
  376.  
  377.  
  378.  
  379.  
  380.  
  381.  
  382.  
  383.  
  384.  
  385.  
  386.  
  387.  
  388.  
  389.  
  390.  
  391.  
  392.  
  393.  
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.  
  401.  
  402.                                       6
  403.  
  404.  
  405.  
  406.  
  407.  
  408.  
  409.  
  410.  
  411.  
  412.  
  413.  
  414. Chapter 1
  415.  
  416.  
  417.  
  418. Installation instructions
  419.  
  420.  
  421.  
  422. This chapter explains how to install Caml Light on your machine.
  423.  
  424.  
  425. 1.1 The Unix version
  426.  
  427. Requirements. Any machine that runs under one of the various flavors of the
  428. Unix operating system, and that has a flat, non-segmented, 32-bit or 64-bit
  429. address space.  4M of RAM, 2M of free disk space.  The graphics library
  430. requires X11 release 4 or later.
  431.  
  432. Installation. The Unix version is distributed in source format, as a
  433. compressed tar file named cl7unix.tar.Z. To extract, move to the directory
  434. where you want the source files to reside, transfer cl7unix.tar.Z to that
  435. directory, and execute
  436.  
  437.         zcat cl7unix.tar.Z | tar xBf -
  438.  
  439. This extracts the source files in the current directory.  The file INSTALL
  440. contains complete instructions on how to configure, compile and install Caml
  441. Light.  Read it and follow the instructions.
  442.  
  443. Troubleshooting. See the file INSTALL.
  444.  
  445.  
  446. 1.2 The Macintosh version
  447.  
  448. Requirements. Any Macintosh with at least 1M of RAM (2M is recommended),
  449. running System 6 or 7.  About 850K of free space on the disk.  The parts of
  450. the Caml Light system that support batch compilation currently require the
  451. Macintosh Programmer's Workshop (MPW) version 3.2.  MPW is Apple's development
  452. environment, and it is distributed by APDA, Apple's Programmers and Developers
  453. Association.  See the file READ ME in the distribution for APDA's address.
  454.  
  455. Installation. Create the folder where the Caml Light files will reside.
  456. Double-click on the file cl7macbin.sea from the distribution.  This displays a
  457. file dialog box.  Open the folder where the Caml Light files will reside, and
  458. click on the Extract button.  This will re-create all files from the
  459. distribution in the Caml Light folder.
  460.   To test the installation, double-click on the application Caml Light.  The
  461. ``Caml Light output'' window should display something like
  462.  
  463.         >       Caml Light version 0.7
  464.  
  465.         #
  466.  
  467.  
  468.                                       7
  469.  
  470.  
  471. Chapter 1.  Installation instructions                                        8
  472.  
  473.  
  474. In the ``Caml Light input'' window, enter 1+2;; and press the Return key.  The
  475. ``Caml Light output'' window should display:
  476.  
  477.         >       Caml Light version 0.7
  478.  
  479.         #1+2;;
  480.         - : int = 3
  481.         #
  482.  
  483. Select ``Quit'' from the ``File'' menu to return to the Finder.
  484.  
  485.   If you have MPW, you can install the batch compilation tools as follows.
  486. The tools and scripts from the tools folder must reside in a place where MPW
  487. will find them as commands.  There are two ways to achieve this result:
  488. either copy the files in the tools folder to the Tools or the Scripts folder
  489. in your MPW folder; or keep the files in the tools folder and add the
  490. following line to your UserStartup file (assuming Caml Light resides in folder
  491. Caml Light on the disk named My HD):
  492.  
  493.         Set Commands "{Commands},My HD:Caml Light:tools:"
  494.  
  495. In either case, you now have to edit the camlc script, and replace the string
  496.  
  497.         Macintosh HD:Caml Light:lib:
  498.  
  499. (in the first line) with the actual pathname of the lib folder.  For example,
  500. if you put Caml Light in folder Caml Light on the disk named My HD, the first
  501. line of camlc should read:
  502.  
  503.         Set stdlib "My HD:Caml Light:lib:"
  504.  
  505. Troubleshooting. Here is one commonly encountered problem.
  506.  
  507. Cannot find file stream.zi
  508.     (Displayed in the ``Caml Light output'' window, with an alert box telling
  509.     you that Caml Light has terminated abnormally.)  This is an installation
  510.     error.  The folder named lib in the distribution must always be in the
  511.     same folder as the Caml Light application.  It's OK to move the
  512.     application to another folder; but remember to move the lib directory to
  513.     the same folder.  (To return to the Finder, first select ``Quit'' from
  514.     the ``File'' menu.)
  515.  
  516.  
  517. 1.3 The PC version
  518.  
  519. Requirements. A PC equipped with a 80386, 80486 or Pentium processor, running
  520. MS-DOS version 3.3 or later.  Older Intel processors (8086, 80286) are no
  521. longer supported.  2M of RAM. About 1.2M of free space on the disk.  The
  522. graphics primitives require a VGA or SuperVGA video card.
  523.  
  524. Installation. In the following, we assume that the distribution files resides
  525. in drive A:, and that the hard disk on which you are installing Caml Light is
  526. drive C:.  If this is not the case, replace A: and C: by the appropriate
  527. drives.
  528.   Create a directory on the hard disk where Caml Light will reside.  In the
  529. following, we assume that this directory is named C:\caml.  If you choose a
  530. different directory, replace C:\caml in the following by the appropriate
  531. absolute path name.  Then, execute the following commands:
  532.  
  533.  
  534. Chapter 1.   Installation instructions                                       9
  535.  
  536.  
  537.         cd C:\caml
  538.         A:pkunzip -d A:cl7pc
  539.  
  540. (Be careful not to omit the -d option to pkunzip.)  This extracts all files in
  541. the C:\caml directory.
  542.   Select or create a directory where Caml Light will put its temporary files.
  543. Many machines already have a C:\tmp directory for that purpose.  If it does
  544. not exist, create it.
  545.   For the remainder of the configuration process, you will have to determine
  546. two things:
  547.  
  548.  -  does your machine contain floating-point hardware --- that is, a 387
  549.     coprocessor, a 486DX or Pentium processor, or a 487SX (co-)processor?
  550.     (If you really don't know, assume no floating-point hardware.)
  551.  
  552.  -  what kind of SuperVGA card do you have?  Caml Light has graphics
  553.     primitives that work on any VGA card in 320x200 pixels, 256 colors, but
  554.     it can take advantage of the extra possibilities of various SuperVGA
  555.     cards to work at higher resolution.  To do so, you must determine which
  556.     chipset is used in your SuperVGA card.  Re-read the documentation for the
  557.     card, then look at the files with extension .GRD or .GRN (the graphics
  558.     drivers) in directory C:\caml\dev, and find one whose name seems to match
  559.     the name of the chipset.  If you can't determine which graphics driver to
  560.     use, don't worry:  you'll stick with the default VGA graphics, that's
  561.     all.
  562.  
  563. Now, edit the C:\autoexec.bat file, in order to:
  564.  
  565.  -  Add C:\caml\bin to the PATH variable; that is, transform the line that
  566.     reads
  567.  
  568.  
  569.             SET PATH=C:\dos;...
  570.  
  571.  
  572.     into
  573.  
  574.  
  575.             SET PATH=C:\dos;...;C:\caml\bin
  576.  
  577.  
  578.  -  Insert the following lines
  579.  
  580.  
  581.             SET CAMLLIB=C:\caml\lib
  582.             SET GO32TMP=C:\tmp
  583.  
  584.  
  585.  -  If your machine has floating-point hardware, insert the following line:
  586.  
  587.  
  588.             SET GO32=driver C:\caml\dev\graph.grd gw 640 gh 480
  589.  
  590.  
  591.     where graph.grd stands for the name of the graphics driver for your
  592.     SuperVGA card, as determined above.  The 640 and 480 specify the default
  593.     graphics resolution to use; you can put 800 and 600, or 1024 and 768
  594.     instead, depending on your taste and the capabilities of your card.
  595.  
  596.  
  597. Chapter 1.   Installation instructions                                      10
  598.  
  599.  
  600.     If you were unable to determine the correct graphics driver, do not
  601.     insert anything, leaving the GO32 variable undefined.
  602.  
  603.  -  If your machine has no floating-point hardware, insert the following
  604.     line:
  605.  
  606.  
  607.     SET GO32=emu C:\caml\dev\emu387 driver C:\caml\dev\graph.grd gw 640 gh 480
  608.  
  609.  
  610.     where graph.grd stands for the name of the graphics driver for your
  611.     SuperVGA card, as determined above.  As explained in the previous item,
  612.     you can choose another default graphics resolution instead of 640 and
  613.     480.
  614.  
  615.     If you were unable to determine the correct graphics driver, insert the
  616.     following line instead:
  617.  
  618.  
  619.             SET GO32=emu C:\caml\dev\emu387
  620.  
  621.  
  622. Then, save the autoexec.bat file and restart the machine.  To test the
  623. installation, execute:
  624.  
  625.         camlc -v
  626.  
  627. The camlc command should print something like:
  628.  
  629.         The Caml Light system for the 80386 PC, version 0.7
  630.           (standard library from C:\caml\lib)
  631.         The Caml Light runtime system, version 0.7
  632.         The Caml Light compiler, version 0.7
  633.         The Caml Light linker, version 0.7
  634.  
  635. Then, execute:
  636.  
  637.         caml
  638.  
  639. The caml command should print something like:
  640.  
  641.         >       Caml Light version 0.7
  642.  
  643.         #
  644.  
  645. In response to the # prompt, type:
  646.  
  647.         quit();;
  648.  
  649. This should get you back to the DOS command interpreter.
  650.  
  651. Troubleshooting. Here are some commonly encountered problems.
  652.  
  653. Cannot find the bytecode file or camlrun.exe: No such file
  654.     The installation has been performed incorrectly.  Double-check the
  655.     autoexec.bat file for errors in setting the PATH and CAMLLIB variables.
  656.  
  657.  
  658. Chapter 1.   Installation instructions                                      11
  659.  
  660.  
  661. CPU must be a 386 to run this program
  662.     Self-explanatory.  It's about time you buy a 386 PC or better.
  663.  
  664. CPU must be in REAL mode (not V86 mode) to run this program
  665.     Ah.  That's a tricky one.  A number of utility programs switch the 80386
  666.     processor to a particular mode, called ``Virtual 86'' or ``V86'' mode,
  667.     that prevents 32-bit protected-mode applications like the 80386 PC
  668.     version of Caml Light from starting.  These programs include:
  669.  
  670.  
  671.      -  device drivers that provide memory management services
  672.  
  673.      -  device drivers that provide enhanced debugging possibilities, such as
  674.         tdh386.sys from Turbo Debugger.
  675.  
  676.  
  677.     The 80386 PC version cannot start when any of these programs is active.
  678.     To solve the problem, remove the guilty device drivers from your
  679.     config.sys file.
  680.  
  681.     On the other hand, the 80386 PC version knows how to cohabit with
  682.     DPMI-compliant or VCPI-compliant environments and memory managers.  These
  683.     include Windows 3, Desqview, and the EMM386, QEMM386 and 386MAX memory
  684.     managers.  In the case of EMM386.EXE from the MS-DOS distribution, EMS
  685.     must be enabled (do not give it the NOEMS option).  If you run the 80386
  686.     PC under a VCPI-compliant memory manager, configure the memory manager so
  687.     that it allocates at least 1M of EMS, and preferably 2M or more.
  688.  
  689. Caml Light runs slowly and does a lot of disk accesses
  690.     When Caml Light cannot allocate the RAM it requires, it starts paging to
  691.     a disk file, which considerably slows down execution.  To avoid this,
  692.     make sure that at least 1M or memory is available to Caml Light, and
  693.     preferably 2M. Caml Light uses XMS memory if you are not running under a
  694.     VCPI-compliant memory manager, and EMS memory if you are running under a
  695.     VCPI-compliant memory manager.  In the latter case, make sure to
  696.     configure the memory manager so that it can allocate enough EMS.
  697.  
  698.  
  699.  
  700.  
  701.  
  702.  
  703.  
  704.  
  705.  
  706.  
  707.  
  708.  
  709.  
  710.  
  711.  
  712.  
  713.  
  714.  
  715.  
  716.  
  717.  
  718.  
  719.  
  720.  
  721.                                    Part II
  722.  
  723.  
  724.  
  725.                    The Caml Light language reference manual
  726.  
  727.  
  728.  
  729.  
  730.  
  731.  
  732.  
  733.  
  734.  
  735.  
  736.  
  737.  
  738.  
  739.  
  740.  
  741.  
  742.  
  743.  
  744.  
  745.  
  746.  
  747.  
  748.  
  749.  
  750.  
  751.  
  752.  
  753.  
  754.  
  755.  
  756.  
  757.  
  758.  
  759.  
  760.  
  761.  
  762.                                       12
  763.  
  764.  
  765.  
  766.  
  767.  
  768.  
  769.  
  770.  
  771.  
  772.  
  773.  
  774. Chapter 2
  775.  
  776.  
  777.  
  778. The core Caml Light language
  779.  
  780.  
  781.  
  782.  
  783. Foreword
  784.  
  785. This document is intended as a reference manual for the Caml Light language.
  786. It lists all language constructs, and gives their precise syntax and informal
  787. semantics.  It is by no means a tutorial introduction to the language:  there
  788. is not a single example.  A good working knowledge of the language, as
  789. provided by the companion tutorial Functional programming using Caml Light, is
  790. assumed.
  791.   No attempt has been made at mathematical rigor:  words are employed with
  792. their intuitive meaning, without further definition.  As a consequence, the
  793. typing rules have been left out, by lack of the mathematical framework
  794. required to express them, while they are definitely part of a full formal
  795. definition of the language.  The reader interested in truly formal
  796. descriptions of languages from the ML family is referred to The definition of
  797. Standard ML and Commentary on Standard ML, by Milner, Tofte and Harper, MIT
  798. Press.
  799.  
  800. Warning
  801.  
  802. Several implementations of the Caml Light language are available, and they
  803. evolve at each release.  Consequently, this document carefully distinguishes
  804. the language and its implementations.  Implementations can provide extra
  805. language constructs; moreover, all points left unspecified in this reference
  806. manual can be interpreted differently by the implementations.  The purpose of
  807. this reference manual is to specify those features that all implementations
  808. must provide.
  809.  
  810. Notations
  811.  
  812. The syntax of the language is given in BNF-like notation.  Terminal symbols
  813. are set in typewriter font (like this).  Non-terminal symbols are set in
  814. italic font (like that).  Square brackets [...] denote optional components.
  815. Curly brackets {...} denotes zero, one or several repetitions of the enclosed
  816. components.  Curly bracket with a trailing plus sign {...}+ denote one or
  817. several repetitions of the enclosed components.  Parentheses (...) denote
  818. grouping.
  819.  
  820.  
  821.  
  822.  
  823.  
  824.  
  825.  
  826.  
  827.                                       13
  828.  
  829.  
  830. Chapter 2.   The core Caml Light language                                   14
  831.  
  832.  
  833. 2.1 Lexical conventions
  834.  
  835. Blanks
  836.  
  837. The following characters are considered as blanks:  space, newline, horizontal
  838. tabulation, carriage return, line feed and form feed.  Blanks are ignored, but
  839. they separate adjacent identifiers, literals and keywords that would otherwise
  840. be confused as one single identifier, literal or keyword.
  841.  
  842. Comments
  843.  
  844. Comments are introduced by the two characters (*, with no intervening blanks,
  845. and terminated by the characters *), with no intervening blanks.  Comments are
  846. treated as blank characters.  Comments do not occur inside string or character
  847. literals.  Nested comments are correctly handled.
  848.  
  849. Identifiers
  850.  
  851.                     ident  ::= letter {letter | 0...9 | _}
  852.                    letter  ::= A...Z | a...z
  853.  
  854.   Identifiers are sequences of letters, digits and _ (the underscore
  855. character), starting with a letter.  Letters contain at least the 52 lowercase
  856. and uppercase letters from the ASCII set.  Implementations can recognize as
  857. letters other characters from the extended ASCII set.  Identifiers cannot
  858. contain two adjacent underscore characters (__).  Implementation may limit the
  859. number of characters of an identifier, but this limit must be above 256
  860. characters.  All characters in an identifier are meaningful.
  861.  
  862. Integer literals
  863.  
  864.          integer-literal  ::= [-] {0...9}+
  865.                             | [-] (0x | 0X) {0...9 | A...F | a...f}+
  866.                             | [-] (0o | 0O) {0...7}+
  867.                             | [-] (0b | 0B) {0...1}+
  868.  
  869.   An integer literal is a sequence of one or more digits, optionally preceded
  870. by a minus sign.  By default, integer literals are in decimal (radix 10).  The
  871. following prefixes select a different radix:
  872.                        --------------------------------
  873.                        |Prefix|Radix                  |
  874.                        --------------------------------
  875.                        |0x, 0X|hexadecimal (radix 16) |
  876.                        |0o, 0O|octal (radix 8)        |
  877.                        |0b, 0B|binary (radix 2)       |
  878.                        --------------------------------
  879.  
  880. (The initial 0 is the digit zero; the O for octal is the letter O.)
  881.  
  882. Floating-point literals
  883.  
  884.    float-literal  ::=  [-] {0...9}+ [. {0...9}] [(e | E) [+ | -] {0...9}+]
  885.  
  886.   Floating-point decimals consist in an integer part, a decimal part and an
  887. exponent part.  The integer part is a sequence of one or more digits,
  888. optionally preceded by a minus sign.  The decimal part is a decimal point
  889. followed by zero, one or more digits.  The exponent part is the character e or
  890. E followed by an optional + or - sign, followed by one or more digits.  The
  891. decimal part or the exponent part can be omitted, but not both to avoid
  892. ambiguity with integer literals.
  893.  
  894.  
  895. Chapter 2.  The core Caml Light language                                    15
  896.  
  897.  
  898. Character literals
  899.  
  900.                char-literal  ::= ` regular-char `
  901.                                | ` \ (\ | ` | n | t | b | r) `
  902.                                | ` \ (0...9) (0...9) (0...9) `
  903.  
  904.   Character literals are delimited by ` (backquote) characters.  The two
  905. backquotes enclose either one character different from ` and \, or one of the
  906. escape sequences below:
  907.            --------------------------------------------------------
  908.            |Sequence|Character denoted                            |
  909.            --------------------------------------------------------
  910.            |\\      |backslash (\)                                |
  911.            |\`      |backquote (`)                                |
  912.            |\n      |newline (LF)                                 |
  913.            |\r      |return (CR)                                  |
  914.            |\t      |horizontal tabulation (TAB)                  |
  915.            |\b      |backspace (BS)                               |
  916.            |\ddd    |the character with ASCII code ddd in decimal |
  917.            --------------------------------------------------------
  918.  
  919. String literals
  920.  
  921.                  string-literal  ::= " {string-character} "
  922.                string-character  ::= regular-char
  923.                                    | \ (\ | " | n | t | b | r)
  924.                                    | \ (0...9) (0...9) (0...9)
  925.  
  926.   String literals are delimited by " (double quote) characters.  The two
  927. double quotes enclose a sequence of either characters different from " and \,
  928. or escape sequences from the table below:
  929.            --------------------------------------------------------
  930.            |Sequence|Character denoted                            |
  931.            --------------------------------------------------------
  932.            |\\      |backslash (\)                                |
  933.            |\"      |double quote (")                             |
  934.            |\n      |newline (LF)                                 |
  935.            |\r      |return (CR)                                  |
  936.            |\t      |horizontal tabulation (TAB)                  |
  937.            |\b      |backspace (BS)                               |
  938.            |\ddd    |the character with ASCII code ddd in decimal |
  939.            --------------------------------------------------------
  940.  
  941.                                                       16
  942.   Implementations must support string literals up to 2  -1 characters in
  943. length (65535 characters).
  944.  
  945. Keywords
  946.  
  947. The identifiers below are reserved as keywords, and cannot be employed
  948. otherwise:
  949.  
  950.         and    as     begin       do      done      downto
  951.         else   end    exception   for     fun       function
  952.         if     in     let         match   mutable   not
  953.         of     or     prefix      rec     then      to
  954.         try    type   value       where   while     with
  955.  
  956. The following character sequences are also keywords:
  957.  
  958.         #    !    !=   &    (    )    *    *.   +    +.
  959.         ,    -    -.   ->   .    .(   /    /.   :    ::
  960.  
  961.  
  962. Chapter 2.   The core Caml Light language                                   16
  963.  
  964.  
  965.         :=   ;    ;;   <    <.   <-   <=   <=.  <>   <>.
  966.         =    =.   ==   >    >.   >=   >=.  @    [    [|
  967.         ]    ^    _    __   {    |    |]   }    '
  968.  
  969. Ambiguities
  970.  
  971. Lexical ambiguities are resolved according to the ``longest match'' rule:
  972. when a character sequence can be decomposed into two tokens in several
  973. different ways, the decomposition retained is the one with the longest first
  974. token.
  975.  
  976.  
  977. 2.2 Global names
  978.  
  979. Global names are used to denote value variables, value constructors (constant
  980. or non-constant), type constructors, and record labels.  Internally, a global
  981. name consists of two parts:  the name of the defining module (the module
  982. name), and the name of the global inside that module (the local name).  The
  983. two parts of the name must be valid identifiers.  Externally, global names
  984. have the following syntax:
  985.  
  986.                        global-name  ::= ident
  987.                                       | ident __ ident
  988.  
  989. The form ident __ ident is called a qualified name.  The first identifier is
  990. the module name, the second identifier is the local name.  The form ident is
  991. called an unqualified name.  The identifier is the local name; the module name
  992. is omitted.  The compiler infers this module name following the completion
  993. rules given below, therefore transforming the unqualified name into a full
  994. global name.
  995.   To complete an unqualified identifier, the compiler checks a list of
  996. modules, the opened modules, to see if they define a global with the same
  997. local name as the unqualified identifier.  When one is found, the identifier
  998. is completed into the full name of that global.  That is, the compiler takes
  999. as module name the name of an opened module that defines a global with the
  1000. same local name as the unqualified identifier.  If several modules satisfy
  1001. this condition, the one that comes first in the list of opened modules is
  1002. selected.
  1003.   The list of opened modules always includes the module currently being
  1004. compiled (checked first).  (In the case of a toplevel-based implementation,
  1005. this is the module where all toplevel definitions are entered.)  It also
  1006. includes a number of standard library modules that provide the initial
  1007. environment (checked last).  In addition, the #open and #close directives can
  1008. be used to add or remove modules from that list.  The modules added with #open
  1009. are checked after the module currently being compiled, but before the initial
  1010. standard library modules.
  1011.  
  1012.  
  1013. Chapter 2.   The core Caml Light language                                   17
  1014.  
  1015.  
  1016.               variable  ::=  global-name
  1017.                           |  prefix operator-name
  1018.          operator-name  ::=  + | - | * | / | mod | +. | -. | *. | /.
  1019.                           |  @ | ^ | ! | := | = | <> | == | != | !
  1020.                           |  < | <= | > | <= | <. | <=. | >. | <=.
  1021.                cconstr  ::=  global-name
  1022.                           |  []
  1023.                           |  ()
  1024.               ncconstr  ::=  global-name
  1025.                           |  prefix ::
  1026.             typeconstr  ::=  global-name
  1027.                  label  ::=  global-name
  1028.  
  1029. Depending on the context, global names can stand for global variables
  1030. (variable), constant value constructors (cconstr), non-constant value
  1031. constructors (ncconst), type constructors (typeconstr), or record labels
  1032. (label).  For variables and value constructors, special names built with
  1033. prefix and an operator name are recognized.  The tokens [] and () are also
  1034. recognized as built-in constant constructors (the empty list and the unit
  1035. value).
  1036.   The syntax of the language restricts labels and type constructors to appear
  1037. in certain positions, where no other kind of global names are accepted.  Hence
  1038. labels and type constructors have their own name spaces.  Value constructors
  1039. and value variables live in the same name space:  a global name in value
  1040. position is interpreted as a value constructor if it appears in the scope of a
  1041. type declaration defining that constructor; otherwise, the global name is
  1042. taken to be a value variable.  For value constructors, the type declaration
  1043. determines whether a constructor is constant or not.
  1044.  
  1045.  
  1046. 2.3 Values
  1047.  
  1048. This section describes the kinds of values that are manipulated by Caml Light
  1049. programs.
  1050.  
  1051. 2.3.1 Base values
  1052.  
  1053. Integer numbers
  1054.  
  1055.                                           30     30
  1056. Integer values are integer numbers from -2   to 2  -1, that is -1073741824
  1057. to 1073741823.  Implementations may support a wider range of integer values.
  1058.  
  1059. Floating-point numbers
  1060.  
  1061. Floating-point values are numbers in floating-point representation.
  1062. Everything about floating-point values is implementation-dependent, including
  1063. the range of representable numbers, the number of significant digits, and the
  1064. way floating-point results are rounded.
  1065.  
  1066. Characters
  1067.  
  1068. Character values are represented as 8-bit integers between 0 and 255.
  1069. Character codes between 0 and 127 are interpreted following the ASCII
  1070. standard.  The interpretation of character codes between 128 and 255 is
  1071. implementation-dependent.
  1072.  
  1073.  
  1074. Chapter 2.   The core Caml Light language                                   18
  1075.  
  1076.  
  1077. Character strings
  1078.  
  1079. String values are finite sequences of characters.  Implementations must
  1080.                        16
  1081. support strings up to 2  -1 characters in length (65535 characters).
  1082. Implementations may support longer strings.
  1083.  
  1084. 2.3.2 Tuples
  1085.  
  1086. Tuples of values are written (v1,...,vn), standing for the n-tuple of values
  1087.                             14
  1088. v1 to vn.  Tuples of up to 2  -1 elements (16383 elements) must be
  1089. supported, though implementations may support tuples with more elements.
  1090.  
  1091. 2.3.3 Records
  1092.  
  1093. Record values are labeled tuples of values.  The record value written
  1094. {label1=v1 ;...;labeln =vn} associates the value vi to the record label
  1095.                                           14
  1096. labeli, for i=1...n.  Records with up to 2   -1 fields (16383 fields) must be
  1097. supported, though implementations may support records with more fields.
  1098.  
  1099. 2.3.4 Arrays
  1100.  
  1101. Arrays are finite, variable-sized sequences of values of the same type.
  1102.                         14
  1103. Arrays of length up to 2  -1 (16383 elements) must be supported, though
  1104. implementations may support larger arrays.
  1105.  
  1106. 2.3.5 Variant values
  1107.  
  1108. Variant values are either a constant constructor, or a pair of a non-constant
  1109. constructor and a value.  The former case is written cconstr; the latter case
  1110. is written ncconstr(v), where v is said to be the argument of the non-constant
  1111. constructor ncconstr.
  1112.   The following constants are treated like built-in constant constructors:
  1113.                         ------------------------------
  1114.                          Constant Constructor
  1115.                         ------------------------------
  1116.                          false    the boolean false
  1117.                          true     the boolean true
  1118.                          ()       the ``unit'' value
  1119.                          []       the empty list
  1120.                         ------------------------------
  1121.  
  1122. 2.3.6 Functions
  1123.  
  1124. Functional values are mappings from values to values.
  1125.  
  1126.  
  1127. 2.4 Type expressions
  1128.  
  1129.                typexpr  ::= ' ident
  1130.                           | ( typexpr )
  1131.                           | typexpr -> typexpr
  1132.                           | typexpr {* typexpr}+
  1133.                           | typeconstr
  1134.                           | typexpr typeconstr
  1135.                           | ( typexpr {, typexpr} ) typeconstr
  1136.  
  1137.  
  1138. Chapter 2.   The core Caml Light language                                   19
  1139.  
  1140.  
  1141.   The table below shows the relative precedences and associativity of
  1142. operators and non-closed type constructions.  The constructions with higher
  1143. precedences come first.
  1144.                 ---------------------------------------------
  1145.                 |Operator                     |Associativity |
  1146.                 ---------------------------------------------
  1147.                 |Type constructor application |--            |
  1148.                 |*                            |--            |
  1149.                 |->                           |right         |
  1150.                 ---------------------------------------------
  1151.  
  1152.   Type expressions denote types in definitions of data types as well as in
  1153. type constraints over patterns and expressions.
  1154.  
  1155. Type variables
  1156.  
  1157. The type expression ' ident stands for the type variable named ident.  In data
  1158. type definitions, type variables are names for the data type parameters.  In
  1159. type constraints, they represent unspecified types that can be instantiated by
  1160. any type to satisfy the type constraint.
  1161.  
  1162. Parenthesized types
  1163.  
  1164. The type expression ( typexpr ) denotes the same type as typexpr.
  1165.  
  1166. Function types
  1167.  
  1168. The type expression typexpr1 -> typexpr2 denotes the type of functions
  1169. mapping arguments of type typexpr1 to results of type typexpr2.
  1170.  
  1171. Tuple types
  1172.  
  1173. The type expression typexpr1 *...* typexprn denotes the type of tuples whose
  1174. elements belong to types typexpr1,...typexprn respectively.
  1175.  
  1176. Constructed types
  1177.  
  1178. Type constructors with no parameter, as in typeconstr, are type expressions.
  1179.   The type expression typexpr typeconstr, where typeconstr is a type
  1180. constructor with one parameter, denotes the application of the unary type
  1181. constructor typeconstr to the type typexpr.
  1182.   The type expression (typexpr1,...,typexprn) typeconstr, where typeconstr is
  1183. a type constructor with n parameters, denotes the application of the n-ary
  1184. type constructor typeconstr to the types typexpr1 through typexprn.
  1185.  
  1186. 2.5 Constants
  1187.  
  1188.                         constant  ::= integer-literal
  1189.                                     | float-literal
  1190.                                     | char-literal
  1191.                                     | string-literal
  1192.                                     | cconstr
  1193.  
  1194.   The syntactic class of constants comprises literals from the four base types
  1195. (integers, floating-point numbers, characters, character strings), and
  1196. constant constructors.
  1197.  
  1198.  
  1199. Chapter 2.   The core Caml Light language                                   20
  1200.  
  1201.  
  1202. 2.6 Patterns
  1203.  
  1204.             pattern  ::=  ident
  1205.                        |  _
  1206.                        |  pattern as ident
  1207.                        |  ( pattern )
  1208.                        |  ( pattern : typexpr )
  1209.                        |  pattern | pattern
  1210.                        |  constant
  1211.                        |  ncconstr pattern
  1212.                        |  pattern , pattern {, pattern}
  1213.                        |  { label = pattern {; label = pattern} }
  1214.                        |  [ ]
  1215.                        |  [ pattern {; pattern} ]
  1216.                        |  pattern :: pattern
  1217.  
  1218.   The table below shows the relative precedences and associativity of
  1219. operators and non-closed pattern constructions.  The constructions with higher
  1220. precedences come first.
  1221.                    ----------------------------------------
  1222.                    |Operator               |Associativity |
  1223.                    ----------------------------------------
  1224.                    |Constructor application|--            |
  1225.                    |::                     |right         |
  1226.                    |,                      |--            |
  1227.                    ||                      |left          |
  1228.                    |as                     |--            |
  1229.                    ----------------------------------------
  1230.  
  1231.   Patterns are templates that allow selecting data structures of a given
  1232. shape, and binding identifiers to components of the data structure.  This
  1233. selection operation is called pattern matching; its outcome is either ``this
  1234. value does not match this pattern'', or ``this value matches this pattern,
  1235. resulting in the following bindings of identifiers to values''.
  1236.  
  1237. Variable patterns
  1238.  
  1239. A pattern that consists in an identifier matches any value, binding the
  1240. identifier to the value.  The pattern _ also matches any value, but does not
  1241. bind any identifier.
  1242.  
  1243. Alias patterns
  1244.  
  1245. The pattern pattern1 as ident matches the same values as pattern1.  If the
  1246. matching against pattern1 is successful, the identifier ident is bound to the
  1247. matched value, in addition to the bindings performed by the matching against
  1248. pattern1.
  1249.  
  1250. Parenthesized patterns
  1251.  
  1252. The pattern ( pattern1 ) matches the same values as pattern1.  A type
  1253. constraint can appear in a parenthesized patterns, as in
  1254. ( pattern1 : typexpr ).  This constraint forces the type of pattern1 to be
  1255. compatible with type.
  1256.  
  1257. ``Or'' patterns
  1258.  
  1259. The pattern pattern1 | pattern2 represents the logical ``or'' of the two
  1260. patterns pattern1 and pattern2.  A value matches pattern1 | pattern2 either
  1261. if it matches pattern1 or if it matches pattern2.  The two sub-patterns
  1262.  
  1263.  
  1264. Chapter 2.   The core Caml Light language                                   21
  1265.  
  1266.  
  1267. pattern1 and pattern2 must contain no identifiers.  Hence no bindings are
  1268. returned by matching against an ``or'' pattern.
  1269.  
  1270. Constant patterns
  1271.  
  1272. A pattern consisting in a constant matches the values that are equal to this
  1273. constant.
  1274.  
  1275. Variant patterns
  1276.  
  1277. The pattern ncconstr pattern1 matches all variants whose constructor is equal
  1278. to ncconstr, and whose argument matches pattern1.
  1279.   The pattern pattern1 :: pattern2 matches non-empty lists whose heads match
  1280. pattern1, and whose tails match pattern2.  This pattern behaves like
  1281. prefix :: ( pattern1 , pattern2 ).
  1282.   The pattern [ pattern1 ;...; patternn ] matches lists of length n whose
  1283. elements match pattern1 ...patternn, respectively.  This pattern behaves like
  1284. pattern1 ::...:: patternn :: [].
  1285.  
  1286. Tuple patterns
  1287.  
  1288. The pattern pattern1 ,..., patternn matches n-tuples whose components match
  1289. the patterns pattern1 through patternn.  That is, the pattern matches the
  1290. tuple values (v1,...,vn) such that patterni matches vi for i =1, ...,n.
  1291.  
  1292. Record patterns
  1293.  
  1294. The pattern { label1 = pattern1 ;...; labeln = patternn } matches records
  1295. that define at least the labels label1 through labeln, and such that the
  1296. value associated to labeli match the pattern patterni, for i= 1,...,n.  The
  1297. record value can define more labels than label1 ...labeln; the values
  1298. associated to these extra labels are not taken into account for matching.
  1299.  
  1300.  
  1301. Chapter 2.   The core Caml Light language                                   22
  1302.  
  1303.  
  1304. 2.7 Expressions
  1305.  
  1306.  
  1307.              expr  ::=  ident
  1308.                      |  variable
  1309.                      |  constant
  1310.                      |  ( expr )
  1311.                      |  begin expr end
  1312.                      |  ( expr : typexpr )
  1313.                      |  expr , expr {, expr}
  1314.                      |  ncconstr expr
  1315.                      |  expr :: expr
  1316.                      |  [ expr {; expr} ]
  1317.                      |  [| expr {; expr} |]
  1318.                      |  { label = expr {; label = expr} }
  1319.                      |  expr expr
  1320.                      |  prefix-op expr
  1321.                      |  expr infix-op expr
  1322.                      |  expr . label
  1323.                      |  expr . label <- expr
  1324.                      |  expr .( expr )
  1325.                      |  expr .( expr ) <- expr
  1326.                      |  expr & expr
  1327.                      |  expr or expr
  1328.                      |  if expr then expr [else expr]
  1329.                      |  while expr do expr done
  1330.                      |  for ident = expr (to | downto) expr do expr done
  1331.                      |  expr ; expr
  1332.                      |  match expr with simple-matching
  1333.                      |  fun multiple-matching
  1334.                      |  function simple-matching
  1335.                      |  try expr with simple-matching
  1336.                      |  let [rec] let-binding {and let-binding} in expr
  1337.   simple-matching  ::=  pattern -> expr {| pattern -> expr}
  1338. multiple-matching  ::=  pattern-list -> expr {| pattern-list -> expr}
  1339.      pattern-list  ::=  pattern {pattern}
  1340.       let-binding  ::=  pattern = expr
  1341.                      |  variable pattern-list = expr
  1342.         prefix-op  ::=  - | -. | !
  1343.          infix-op  ::=  + | - | * | / | mod | +. | -. | *. | /. | @ | ^ | ! | :=
  1344.                      |  = | <> | == | != | < | <= | > | <= | <. | <=. | >. | <=.
  1345.  
  1346.   The table below shows the relative precedences and associativity of
  1347. operators and non-closed constructions.  The constructions with higher
  1348. precedence come first.
  1349.  
  1350.  
  1351. Chapter 2.   The core Caml Light language                                   23
  1352.  
  1353.                 ---------------------------------------------
  1354.                 |Construction or operator     |Associativity |
  1355.                 ---------------------------------------------
  1356.                 |!                            |--            |
  1357.                 |.   .(                       |--            |
  1358.                 |function application         |right         |
  1359.                 |constructor application      |--            |
  1360.                 |-   -.  (prefix)             |--            |
  1361.                 |mod                          |left          |
  1362.                 |*   *.   /   /.              |left          |
  1363.                 |+   +.   -   -.              |left          |
  1364.                 |::                           |right         |
  1365.                 |@ ^                          |right         |
  1366.                 |comparisons (=  ==  <  etc.) |left          |
  1367.                 |not                          |--            |
  1368.                 |&                            |left          |
  1369.                 |or                           |left          |
  1370.                 |,                            |--            |
  1371.                 |<-   :=                      |right         |
  1372.                 |if                           |--            |
  1373.                 |;                            |right         |
  1374.                 |let match fun function try   |--            |
  1375.                 ---------------------------------------------
  1376.  
  1377. 2.7.1 Simple expressions
  1378.  
  1379. Constants
  1380.  
  1381. Expressions consisting in a constant evaluate to this constant.
  1382.  
  1383. Variables
  1384.  
  1385. Expressions consisting in a variable evaluate to the value bound to this
  1386. variable in the current evaluation environment.  The variable can be either a
  1387. qualified identifier or a simple identifier.  Qualified identifiers always
  1388. denote global variables.  Simple identifiers denote either a local variable,
  1389. if the identifier is locally bound, or a global variable, whose full name is
  1390. obtained by qualifying the simple identifier, as described in section 2.2.
  1391.  
  1392. Parenthesized expressions
  1393.  
  1394. The expressions ( expr ) and begin expr end have the same value as expr.  Both
  1395. constructs are semantically equivalent, but it is good style to use
  1396. begin...end inside control structures:
  1397.  
  1398.         if ... then begin ... ; ... end else begin ... ; ... end
  1399.  
  1400. and (...) for the other grouping situations.
  1401.   Parenthesized expressions can contain a type constraint, as in
  1402. ( expr : type ).  This constraint forces the type of expr to be compatible
  1403. with type.
  1404.  
  1405. Function abstraction
  1406.  
  1407. The most general form of function abstraction is:
  1408.  
  1409.                                 1            m
  1410.                     fun  pattern1 ... pattern1  -> expr1
  1411.                       |  ...    1            m
  1412.                       |  patternn ... patternn  -> exprn
  1413.  
  1414.  
  1415. Chapter 2.   The core Caml Light language                                   24
  1416.  
  1417.  
  1418.  This expression evaluates to a functional value with m curried arguments.
  1419. When this function is applied to m values v1 ... vm, the values are matched
  1420.                                 1          m
  1421. against each pattern row patterni...patterni for i from 1 to n.  If one of
  1422. these matchings succeeds, that is if the value vj matches the pattern
  1423.        j
  1424. patterni for all j=1, ...,m, then the expression expri associated to the
  1425. selected pattern row is evaluated, and its value becomes the value of the
  1426. function application.  The evaluation of expri takes place in an environment
  1427. enriched by the bindings performed during the matching.
  1428.   If several pattern rows match the arguments, the one that occurs first in
  1429. the function definition is selected.  If none of the pattern rows matches the
  1430. argument, the exception Match_failure is raised.
  1431.   If the function above is applied to less than m arguments, a functional
  1432. value is returned, that represents the partial application of the function to
  1433. the arguments provided.  This partial application is a function that, when
  1434. applied to the remaining arguments, matches all arguments against the pattern
  1435. rows as described above.  Matching does not start until all m arguments have
  1436. been provided to the function; hence, partial applications of the function to
  1437. less than m arguments never raise Match_failure.
  1438.   All pattern rows in the function body must contain the same number of
  1439. patterns.  A variable must not be bound more than once in one pattern row.
  1440.   Functions with only one argument can be defined with the function keyword
  1441. instead of fun:
  1442.  
  1443.                         function  pattern1  -> expr1
  1444.                                |  ...
  1445.                                |  patternn  -> exprn
  1446.  
  1447.  The function thus defined behaves exactly as described above.  The only
  1448. difference between the two forms of function definition is how a parsing
  1449. ambiguity is resolved.  The two forms cconstr  pattern (two patterns in a row)
  1450. and ncconstr  pattern (one pattern) cannot be distinguished syntactically.
  1451. Function definitions introduced by fun resolve the ambiguity to the former
  1452. form; function definitions introduced by function resolve it to the latter
  1453. form (the former form makes no sense in this case).
  1454.  
  1455. Function application
  1456.  
  1457. Function application is denoted by juxtaposition of expressions.  The
  1458. expression expr1 expr2...exprn evaluates the expressions expr1 to exprn.  The
  1459. expression expr1 must evaluate to a functional value, which is then applied
  1460. to the values of expr2,...,exprn.  The order in which the expressions
  1461. expr1,...,exprn are evaluated is not specified.
  1462.  
  1463. Local definitions
  1464.  
  1465. The let and let rec constructs bind variables locally.  The construct
  1466.  
  1467.            let pattern1 = expr1 and...and patternn = exprn in expr
  1468.  
  1469. evaluates expr1...exprn in some unspecified order, then matches their values
  1470. against the patterns pattern1...patternn.  If the matchings succeed, expr is
  1471. evaluated in the environment enriched by the bindings performed during
  1472. matching, and the value of expr is returned as the value of the whole let
  1473. expression.  If one of the matchings fails, the exception Match_failure is
  1474. raised.
  1475.  
  1476.  
  1477. Chapter 2.   The core Caml Light language                                   25
  1478.  
  1479.  
  1480.   An alternate syntax is provided to bind variables to functional values:
  1481. instead of writing
  1482.  
  1483.                    ident = fun pattern1...patternm -> expr
  1484.  
  1485. in a let expression, one may instead write
  1486.  
  1487.                       ident pattern1 ...patternm = expr
  1488.  
  1489. Both forms bind ident to the curried function with m arguments and only one
  1490. case,
  1491.  
  1492.                         pattern1 ...patternm -> expr.
  1493.  
  1494.  
  1495. Recursive definitions of variables are introduced by let rec:
  1496.  
  1497.          let rec pattern1 = expr1 and...and patternn = exprn in expr
  1498.  
  1499. The only difference with the let construct described above is that the
  1500. bindings of variables to values performed by the pattern-matching are
  1501. considered already performed when the expressions expr1 to exprn are
  1502. evaluated.  That is, the expressions expr1 to exprn can reference identifiers
  1503. that are bound by one of the patterns pattern1,...,patternn, and expect them
  1504. to have the same value as in expr, the body of the let rec construct.
  1505.   The recursive definition is guaranteed to behave as described above if the
  1506. expressions expr1 to exprn are function definitions (fun... or function...),
  1507. and the patterns pattern1...patternn consist in a single variable, as in:
  1508.  
  1509.            let rec ident1 = fun...and...and identn = fun...in expr
  1510.  
  1511. This defines ident1...identn as mutually recursive functions local to expr.
  1512. The behavior of other forms of let rec definitions is
  1513. implementation-dependent.
  1514.  
  1515. 2.7.2 Control constructs
  1516.  
  1517. Sequence
  1518.  
  1519. The expression expr1 ; expr2 evaluates expr1 first, then expr2, and returns
  1520. the value of expr2.
  1521.  
  1522. Conditional
  1523.  
  1524. The expression if expr1 then expr2 else expr3 evaluates to the value of expr2
  1525. if expr1 evaluates to the boolean true, and to the value of expr3 if expr1
  1526. evaluates to the boolean false.
  1527.   The else expr3 part can be omitted, in which case it defaults to else ().
  1528.  
  1529. Case expression
  1530.  
  1531. The expression
  1532.  
  1533.                           match  expr
  1534.                            with  pattern1 ->  expr1
  1535.                               |  ...
  1536.                               |  patternn ->  exprn
  1537.  
  1538.  
  1539. Chapter 2.   The core Caml Light language                                   26
  1540.  
  1541.  
  1542.  matches the value of expr against the patterns pattern1 to patternn.  If the
  1543. matching against patterni succeeds, the associated expression expri is
  1544. evaluated, and its value becomes the value of the whole match expression.  The
  1545. evaluation of expri takes place in an environment enriched by the bindings
  1546. performed during matching.  If several patterns match the value of expr, the
  1547. one that occurs first in the match expression is selected.  If none of the
  1548. patterns match the value of expr, the exception Match_failure is raised.
  1549.  
  1550. Boolean operators
  1551.  
  1552. The expression expr1 & expr2 evaluates to true if both expr1 and expr2
  1553. evaluate to true; otherwise, it evaluates to false.  The first component,
  1554. expr1, is evaluated first.  The second component, expr2, is not evaluated if
  1555. the first component evaluates to false.  Hence, the expression expr1 & expr2
  1556. behaves exactly as
  1557.  
  1558.                        if expr1 then expr2 else false.
  1559.  
  1560.   The expression expr1 or expr2 evaluates to true if one of expr1 and expr2
  1561. evaluates to true; otherwise, it evaluates to false.  The first component,
  1562. expr1, is evaluated first.  The second component, expr2, is not evaluated if
  1563. the first component evaluates to true.  Hence, the expression expr1 or expr2
  1564. behaves exactly as
  1565.  
  1566.                        if expr1  then true else expr2.
  1567.  
  1568. Loops
  1569.  
  1570. The expression while expr1 do expr2 done repeatedly evaluates expr2 while
  1571. expr1 evaluates to true.  The loop condition expr1 is evaluated and tested at
  1572. the beginning of each iteration.  The whole while...done expression evaluates
  1573. to the unit value ().
  1574.   The expression for ident = expr1 to expr2 do expr3 done first evaluates the
  1575. expressions expr1 and expr2 (the boundaries) into integer values n and p.
  1576. Then, the loop body expr3 is repeatedly evaluated in an environment where the
  1577. local variable named ident is successively bound to the values  n, n+1, ...,
  1578. p-1, p.  The loop body is never evaluated if n >p.
  1579.   The expression for ident = expr1 downto expr2 do expr3 done first evaluates
  1580. the expressions expr1 and expr2 (the boundaries) into integer values n and p.
  1581. Then, the loop body expr3 is repeatedly evaluated in an environment where the
  1582. local variable named ident is successively bound to the values  n, n-1, ...,
  1583. p+1, p.  The loop body is never evaluated if n <p.
  1584.   In both cases, the whole for expression evaluates to the unit value ().
  1585.  
  1586. Exception handling
  1587.  
  1588. The expression
  1589.  
  1590.                           try   expr
  1591.                           with  pattern1  -> expr1
  1592.                              |  ...
  1593.                              |  patternn  -> exprn
  1594.  
  1595.  evaluates the expression expr and returns its value if the evaluation of expr
  1596. does not raise any exception.  If the evaluation of expr raises an exception,
  1597. the exception value is matched against the patterns pattern1 to patternn.  If
  1598. the matching against patterni succeeds, the associated expression expri is
  1599.  
  1600.  
  1601. Chapter 2.   The core Caml Light language                                   27
  1602.  
  1603.  
  1604. evaluated, and its value becomes the value of the whole try expression.  The
  1605. evaluation of expri takes place in an environment enriched by the bindings
  1606. performed during matching.  If several patterns match the value of expr, the
  1607. one that occurs first in the try expression is selected.  If none of the
  1608. patterns matches the value of expr, the exception value is raised again,
  1609. thereby transparently ``passing through'' the try construct.
  1610.  
  1611. 2.7.3 Operations on data structures
  1612.  
  1613. Products
  1614.  
  1615. The expression expr1 ,..., exprn evaluates to the n-tuple of the values of
  1616. expressions expr1 to exprn.  The evaluation order for the subexpressions is
  1617. not specified.
  1618.  
  1619. Variants
  1620.  
  1621. The expression ncconstr expr evaluates to the variant value whose constructor
  1622. is ncconstr, and whose argument is the value of expr.
  1623.   For lists, some syntactic sugar is provided.  The expression expr1 :: expr2
  1624. stands for the constructor prefix :: applied to the argument
  1625. ( expr1 , expr2 ), and therefore evaluates to the list whose head is the
  1626. value of expr1 and whose tail is the value of expr2.  The expression
  1627. [ expr1 ;...; exprn ] is equivalent to expr1 ::...:: exprn :: [], and
  1628. therefore evaluates to the list whose elements are the values of expr1 to
  1629. exprn.
  1630.  
  1631. Records
  1632.  
  1633. The expression { label1 = expr1 ;...; labeln = exprn } evaluates to the
  1634. record value { label1 = v1 ;...; labeln = vn }, where vi is the value of
  1635. expri for i=1, ...,n.  The labels label1 to labeln must all belong to the
  1636. same record types; all labels belonging to this record type must appear
  1637. exactly once in the record expression, though they can appear in any order.
  1638. The order in which expr1 to exprn are evaluated is not specified.
  1639.   The expression expr1 . label evaluates expr1 to a record value, and returns
  1640. the value associated to label in this record value.
  1641.   The expression expr1 . label <- expr2 evaluates expr1 to a record value,
  1642. which is then modified in-place by replacing the value associated to label in
  1643. this record by the value of expr2.  This operation is permitted only if label
  1644. has been declared mutable in the definition of the record type.  The whole
  1645. expression expr1 . label <- expr2 evaluates to the unit value ().
  1646.  
  1647. Arrays
  1648.  
  1649. The expression [| expr1 ;...; exprn |] evaluates to a n-element array, whose
  1650. elements are initialized with the values of expr1 to exprn respectively.  The
  1651. order in which these expressions are evaluated is unspecified.
  1652.   The expression expr1 .( expr2 ) is equivalent to the application
  1653. vect_item expr1 expr2.  In the initial environment, the identifier vect_item
  1654. resolves to a built-in function that returns the value of element number
  1655. expr2 in the array denoted by expr1.  The first element has number 0; the
  1656. last element has number n-1, where n is the size of the array.  The exception
  1657. Invalid_argument is raised if the access is out of bounds.
  1658.   The expression expr1 .( expr2 ) <- expr3 is equivalent to
  1659. vect_assign expr1 expr2 expr3.  In the initial environment, the identifier
  1660. vect_assign resolves to a built-in function that modifies in-place the array
  1661.  
  1662.  
  1663. Chapter 2.   The core Caml Light language                                   28
  1664.  
  1665.  
  1666. denoted by expr1, replacing element number expr2 by the value of expr3.  The
  1667. exception Invalid_argument is raised if the access is out of bounds.  The
  1668. built-in function returns ().  Hence, the whole expression
  1669. expr1 .( expr2 ) <- expr3 evaluates to the unit value ().
  1670.   This behavior of the two constructs expr1 .( expr2 ) and
  1671. expr1 .( expr2 ) <- expr3 may change if the meaning of the identifiers
  1672. vect_item and vect_assign is changed, either by redefinition or by
  1673. modification of the list of opened modules.  See the discussion below on
  1674. operators.
  1675.  
  1676. 2.7.4 Operators
  1677.  
  1678. The operators written infix-op in the grammar above can appear in infix
  1679. position (between two expressions).  The operators written prefix-op in the
  1680. grammar above can appear in prefix position (in front of an expression).
  1681.   The expression prefix-op expr is interpreted as the application ident expr,
  1682. where ident is the identifier associated to the operator prefix-op in the
  1683. table below.  Similarly, the expression expr1 infix-op expr2 is interpreted
  1684. as the application ident expr1 expr2, where ident is the identifier
  1685. associated to the operator infix-op in the table below.  The identifiers
  1686. written ident above are then evaluated following the rules in section 2.7.1.
  1687. In the initial environment, they evaluate to built-in functions whose behavior
  1688. is described in the table.  The behavior of the constructions prefix-op expr
  1689. and expr1 infix-op expr2 may change if the meaning of the identifiers
  1690. associated to prefix-op or infix-op is changed, either by redefinition of the
  1691. identifiers, or by modification of the list of opened modules, through the
  1692. #open and #close directives.
  1693.  
  1694.  
  1695. Chapter 2.   The core Caml Light language                                   29
  1696.  
  1697.  ---------------------------------------------------------------------------
  1698.  |Operator     |Associated  |Behavior in the default environment            |
  1699.  |             |identifier  |                                               |
  1700.  ---------------------------------------------------------------------------
  1701.  |+            |prefix +    |Integer addition.                              |
  1702.  |- (infix)    |prefix -    |Integer subtraction.                           |
  1703.  |- (prefix)   |minus       |Integer negation.                              |
  1704.  |*            |prefix *    |Integer multiplication.                        |
  1705.  |/            |prefix /    |Integer division.   Raise  Division_by_zero if |
  1706.  |             |            |second  argument  is  zero.    The  result  is |
  1707.  |             |            |unspecified if either argument is negative.    |
  1708.  |mod          |prefix mod  |Integer modulus.    Raise Division_by_zero  if |
  1709.  |             |            |second  argument  is  zero.    The  result  is |
  1710.  |             |            |unspecified if either argument is negative.    |
  1711.  |+.           |prefix +.   |Floating-point addition.                       |
  1712.  |-.  (infix)  |prefix -.   |Floating-point subtraction.                    |
  1713.  |-.  (prefix) |minus_float |Floating-point negation.                       |
  1714.  |*.           |prefix *.   |Floating-point multiplication.                 |
  1715.  |/.           |prefix /.   |Floating-point   division.       Raise   Divi- |
  1716.  |             |            |sion_by_zero if second argument is zero.       |
  1717.  |@            |prefix @    |List concatenation.                            |
  1718.  |^            |prefix ^    |String concatenation.                          |
  1719.  |!            |prefix !    |Dereferencing (return the  current contents of |
  1720.  |             |            |a reference).                                  |
  1721.  |:=           |prefix :=   |Reference  assignment  (update  the  reference |
  1722.  |             |            |given as first argument with  the value of the |
  1723.  |             |            |second argument).                              |
  1724.  |=            |prefix =    |Structural equality test.                      |
  1725.  |<>           |prefix <>   |Structural inequality test.                    |
  1726.  |==           |prefix ==   |Physical equality test.                        |
  1727.  |!=           |prefix !=   |Physical inequality test.                      |
  1728.  |<            |prefix <    |Test ``less than'' on integers.                |
  1729.  |<=           |prefix <=   |Test ``less than or equal '' on integers.      |
  1730.  |>            |prefix >    |Test ``greater than'' on integers.             |
  1731.  |>=           |prefix >=   |Test ``greater than or equal'' on integers.    |
  1732.  |<.           |prefix <.   |Test ``less than'' on floating-point numbers.  |
  1733.  |<=.          |prefix <=.  |Test ``less than or equal '' on floating-point |
  1734.  |             |            |numbers.                                       |
  1735.  |>.           |prefix >.   |Test   ``greater  than''   on   floating-point |
  1736.  |             |            |numbers.                                       |
  1737.  |>=.          |prefix >=.  |Test ``greater  than or  equal'' on  floating- |
  1738.  |             |            |point numbers.                                 |
  1739.  ---------------------------------------------------------------------------
  1740.  
  1741.   The behavior of the +, -, *, /, mod, +., -., *.  or /.  operators is
  1742. unspecified if the result falls outside of the range of representable integers
  1743. or floating-point numbers, respectively.  See chapter 13 for a more precise
  1744. description of the behavior of the operators above.
  1745.  
  1746.  
  1747. 2.8 Global definitions
  1748.  
  1749. This section describes the constructs that bind global identifiers (value
  1750. variables, value constructors, type constructors, record labels).
  1751.  
  1752.  
  1753. Chapter 2.   The core Caml Light language                                   30
  1754.  
  1755.  
  1756. 2.8.1 Type definitions
  1757.  
  1758.    type-definition  ::=  type typedef {and typedef}
  1759.            typedef  ::=  type-params ident = constr-decl {| constr-decl}
  1760.                       |  type-params ident = { label-decl {; label-decl} }
  1761.                       |  type-params ident == typexpr
  1762.                       |  type-params ident
  1763.        type-params  ::=  nothing
  1764.                       |  ' ident
  1765.                       |  ( ' ident {, ' ident} )
  1766.        constr-decl  ::=  ident
  1767.                       |  ident of typexpr
  1768.         label-decl  ::=  ident : typexpr
  1769.                       |  mutable ident : typexpr
  1770.  
  1771.   Type definitions bind type constructors to data types:  either variant
  1772. types, record types, type abbreviations, or abstract data types.
  1773.   Type definitions are introduced by the type keyword, and consist in one or
  1774. several simple definitions, possibly mutually recursive, separated by the and
  1775. keyword.  Each simple definition defines one type constructor.
  1776.   A simple definition consists in an identifier, possibly preceded by one or
  1777. several type parameters, and followed by a data type description.  The
  1778. identifier is the local name of the type constructor being defined.  (The
  1779. module name for this type constructor is the name of the module being
  1780. compiled.)  The optional type parameters are either one type variable ' ident,
  1781. for type constructors with one parameter, or a list of type variables
  1782. (' ident1,...,' identn), for type constructors with several parameters.
  1783. These type parameters can appear in the type expressions of the right-hand
  1784. side of the definition.
  1785.  
  1786. Variant types
  1787.  
  1788. The type definition typeparams ident = constr-decl1 |...| constr-decln
  1789. defines a variant type.  The constructor declarations
  1790. constr-decl1,...,constr-decln describe the constructors associated to this
  1791. variant type.  The constructor declaration ident of typexpr declares the local
  1792. name ident (in the module being compiled) as a non-constant constructor, whose
  1793. argument has type typexpr.  The constructor declaration ident declares the
  1794. local name ident (in the module being compiled) as a constant constructor.
  1795.  
  1796. Record types
  1797.  
  1798. The type definition typeparams ident = { label-decl1 ;...; label-decln }
  1799. defines a record type.  The label declarations label-decl1,...,label-decln
  1800. describe the labels associated to this record type.  The label declaration
  1801. ident : typexpr declares the local name ident in the module being compiled as
  1802. a label, whose argument has type typexpr.  The label declaration
  1803. mutable ident : typexpr behaves similarly; in addition, it allows physical
  1804. modification over the argument to this label.
  1805.  
  1806. Type abbreviations
  1807.  
  1808. The type definition typeparams ident == typexpr defines the type constructor
  1809. ident as an abbreviation for the type expression typexpr.
  1810.  
  1811.  
  1812. Chapter 2.   The core Caml Light language                                   31
  1813.  
  1814.  
  1815. Abstract types
  1816.  
  1817. The type definition typeparams ident defines ident as an abstract type.  When
  1818. appearing in a module interface, this definition allows exporting a type
  1819. constructor while hiding how it is represented in the module implementation.
  1820.  
  1821. 2.8.2 Exception definitions
  1822.  
  1823.       exception-definition  ::= exception constr-decl {and constr-decl}
  1824.  
  1825.   Exception definitions add new constructors to the built-in variant type exn
  1826. of exception values.  The constructors are declared as for a definition of a
  1827. variant type.
  1828.  
  1829.  
  1830. 2.9 Directives
  1831.  
  1832.                         directive  ::= # open string
  1833.                                      | # close string
  1834.                                      | # ident string
  1835.  
  1836.   Directives control the behavior of the compiler.  They apply to the
  1837. remainder of the current compilation unit.
  1838.   The two directives #open and #close modify the list of opened modules, that
  1839. the compiler uses to complete unqualified identifiers, as described in
  1840. section 2.2.  The directive #open string adds the module whose name is given
  1841. by the string constant string to the list of opened modules, in first
  1842. position.  The directive #close string removes the first occurrence of the
  1843. module whose name is given by the string constant string from the list of
  1844. opened modules.
  1845.   Implementations can provide other directives, provided they follow the
  1846. syntax # ident string, where ident is the name of the directive, and the
  1847. string constant string is the argument to the directive.  The behavior of
  1848. these additional directives is implementation-dependent.
  1849.  
  1850.  
  1851. 2.10 Module implementations
  1852.  
  1853.           implementation  ::= {impl-phrase ;;}
  1854.              impl-phrase  ::= expr
  1855.                             | value-definition
  1856.                             | type-definition
  1857.                             | exception-definition
  1858.                             | directive
  1859.         value-definition  ::= let [rec] let-binding {and let-binding}
  1860.  
  1861.   A module implementation consists in a sequence of implementation phrases,
  1862. terminated by double semicolons.  An implementation phrase is either an
  1863. expression, a value definition, a type or exception definition, or a
  1864. directive.  At run-time, implementation phrases are evaluated sequentially, in
  1865. the order in which they appear in the module implementation.
  1866.   Implementation phrases consisting in an expression are evaluated for their
  1867. side-effects.
  1868.   Value definitions bind global value variables in the same way as a
  1869. let...in... expression binds local variables.  The expressions are evaluated,
  1870. and their values are matched against the left-hand sides of the = sides, as
  1871. explained in section 2.7.1.  If the matching succeeds, the bindings of
  1872. identifiers to values performed during matching are interpreted as bindings to
  1873. the global value variables whose local name is the identifier, and whose
  1874.  
  1875.  
  1876. Chapter 2.   The core Caml Light language                                   32
  1877.  
  1878.  
  1879. module name is the name of the module.  If the matching fails, the exception
  1880. Match_failure is raised.  The scope of these bindings is the phrases that
  1881. follow the value definition in the module implementation.
  1882.   Type and exception definitions introduce type constructors, variant
  1883. constructors and record labels as described in sections 2.8.1 and 2.8.2.  The
  1884. scope of these definitions is the phrases that follow the value definition in
  1885. the module implementation.  The evaluation of an implementation phrase
  1886. consisting in a type or exception definition produces no effect at run-time.
  1887.   Directives modify the behavior of the compiler on the subsequent phrases of
  1888. the module implementation, as described in section 2.9.  The evaluation of an
  1889. implementation phrase consisting in a directive produces no effect at
  1890. run-time.  Directives apply only to the module currently being compiled; in
  1891. particular, they have no effect on other modules that refer to globals
  1892. exported by the module being compiled.
  1893.  
  1894.  
  1895. 2.11 Module interfaces
  1896.  
  1897.              interface  ::=  {intf-phrase ;;}
  1898.            intf-phrase  ::=  value-declaration
  1899.                           |  type-definition
  1900.                           |  exception-definition
  1901.                           |  directive
  1902.      value-declaration  ::=  value ident : typexpr {and ident : typexpr}
  1903.  
  1904.   Module interfaces declare the global objects (value variables, type
  1905. constructors, variant constructors, record labels) that a module exports, that
  1906. is, makes available to other modules.  Other modules can refer to these
  1907. globals using qualified identifiers or the #open directive, as explained in
  1908. section 2.2.
  1909.   A module interface consists in a sequence of interface phrases, terminated
  1910. by double semicolons.  An interface phrase is either a value declaration, a
  1911. type definition, an exception definition, or a directive.
  1912.   Value declarations declare global value variables that are exported by the
  1913. module implementation, and the types with which they are exported.  The module
  1914. implementation must define these variables, with types at least as general as
  1915. the types declared in the interface.  The scope of the bindings for these
  1916. global variables extends from the module implementation itself to all modules
  1917. that refer to those variables.
  1918.   Type or exception definitions introduce type constructors, variant
  1919. constructors and record labels as described in sections 2.8.1 and 2.8.2.
  1920. Exception definitions and type definitions that are not abstract type
  1921. declarations also take effect in the module implementation; that is, the type
  1922. constructors, variant constructors and record labels they define are
  1923. considered bound on entrance to the module implementation, and can be referred
  1924. to by the implementation phrases.  Type definitions that are not abstract type
  1925. declarations must not be redefined in the module implementation.  In contrast,
  1926. the type constructors that are declared abstract in a module interface must be
  1927. defined in the module implementation, with the same names.
  1928.   Directives modify the behavior of the compiler on the subsequent phrases of
  1929. the module interface, as described in section 2.9.  Directives apply only to
  1930. the interface currently being compiled; in particular, they have no effect on
  1931. other modules that refer to globals exported by the interface being compiled.
  1932.  
  1933.  
  1934.  
  1935.  
  1936.  
  1937.  
  1938.  
  1939.  
  1940.  
  1941.  
  1942.  
  1943. Chapter 3
  1944.  
  1945.  
  1946.  
  1947. Language extensions
  1948.  
  1949.  
  1950.  
  1951. This chapter describes the language features that are implemented in Caml
  1952. Light, but not described in the Caml Light reference manual.  In contrast with
  1953. the fairly stable kernel language that is described in the reference manual,
  1954. the extensions presented here are still experimental, and may be removed or
  1955. changed in the future.
  1956.  
  1957.  
  1958. 3.1 Streams, parsers, and printers
  1959.  
  1960. Caml Light comprises a built-in type for streams (possibly infinite sequences
  1961. of elements, that are evaluated on demand), and associated stream expressions,
  1962. to build streams, and stream patterns, to destructure streams.  Streams and
  1963. stream patterns provide a natural approach to the writing of recursive-descent
  1964. parsers.
  1965.   Streams are presented by the following extensions to the syntactic classes
  1966. of expressions:
  1967.  
  1968.                expr  ::= ...
  1969.                        | [< >]
  1970.                        | [< stream-component {; stream-component} >]
  1971.                        | function stream-matching
  1972.                        | match expr with stream-matching
  1973.    stream-component  ::= ' expr
  1974.                        | expr
  1975.     stream-matching  ::= stream-pattern -> expr {| stream-pattern -> expr}
  1976.      stream-pattern  ::= [< >]
  1977.                        | [< stream-comp-pat {; stream-comp-pat} >]
  1978.     stream-comp-pat  ::= ' pattern
  1979.                        | expr pattern
  1980.                        | ident
  1981.  
  1982.  
  1983.   Stream expressions are bracketed by [< and >].  They represent the
  1984. concatenation of their components.  The component ' expr represents the
  1985. one-element stream whose element is the value of expr.  The component expr
  1986. represents a sub-stream.  For instance, if both s and t are streams of
  1987. integers, then [<'1; s; t; '2>] is a stream of integers containing the element
  1988. 1, then the elements of s, then those of t, and finally 2.  The empty stream
  1989. is denoted by [< >].
  1990.   Unlike any other kind of expressions in the language, stream expressions are
  1991. submitted to lazy evaluation:  the components are not evaluated when the
  1992. stream is built, but only when they are accessed during stream matching.  The
  1993. components are evaluated once, the first time they are accessed; the following
  1994.  
  1995.  
  1996.                                       33
  1997.  
  1998.  
  1999. Chapter 3.   Language extensions                                            34
  2000.  
  2001.  
  2002. accesses reuse the value computed the first time.
  2003.   Stream patterns, also bracketed by [< and >], describe initial segments of
  2004. streams.  In particular, the stream pattern [< >] matches all streams.  Stream
  2005. pattern components are matched against the corresponding elements of a stream.
  2006. The component ' pattern matches the corresponding stream element against the
  2007. pattern.  The component expr pattern applies the function denoted by expr to
  2008. the current stream, then matches the result of the function against pattern.
  2009. Finally, the component ident simply binds the identifier to the stream being
  2010. matched.  (The current implementation limits ident to appear last in a stream
  2011. pattern.)
  2012.   Stream matching proceeds destructively:  once a component has been matched,
  2013. it is discarded from the stream (by in-place modification).
  2014.   Stream matching proceeds in two steps:  first, a pattern is selected by
  2015. matching the stream against the first components of the stream patterns; then,
  2016. the following components of the selected pattern are checked against the
  2017. stream.  If the following components do not match, the exception Parse_error
  2018. is raised.  There is no backtracking here:  stream matching commits to the
  2019. pattern selected according to the first element.  If none of the first
  2020. components of the stream patterns match, the exception Parse_failure is
  2021. raised.  The Parse_failure exception causes the next alternative to be tried,
  2022. if it occurs during the matching of the first element of a stream, before
  2023. matching has committed to one pattern.
  2024.   See Functional programming using Caml Light for a more gentle introductions
  2025. to streams, and for some examples of their use in writing parsers.  A more
  2026. formal presentation of streams, and a discussion of alternate semantics, can
  2027. be found in Parsers in ML by Michel Mauny and Daniel de Rauglaudre, in the
  2028. proceedings of the 1992 ACM conference on Lisp and Functional Programming.
  2029.  
  2030.  
  2031. 3.2 Guards
  2032.  
  2033. Cases of a pattern matching can include guard expressions, which are arbitrary
  2034. boolean expressions that must evaluate to true for the match case to be
  2035. selected.  Guards occur just before the -> token and are introduced by the
  2036. when keyword:
  2037.  
  2038.                     match  expr
  2039.                      with  pattern1[whencond1]  -> expr1
  2040.                         |  ...
  2041.                         |  patternn[whencondn]  -> exprn
  2042.  
  2043.  (Same syntax for the fun, function, and try ...with constructs.)  During
  2044. matching, if the value of expr matches some pattern patterni which has a
  2045. guard condi, then the expression condi is evaluated (in an environment
  2046. enriched by the bindings performed during matching).  If condi evaluates to
  2047. true, then expri is evaluated and its value returned as the result of the
  2048. matching, as usual.  But if condi evaluates to false, the matching is resumed
  2049. against the patterns following patterni.
  2050.  
  2051. 3.3 Range patterns
  2052.  
  2053. In patterns, Caml Light recognizes the form ` c ` .. ` d ` (two character
  2054. constants separated by ..) as a shorthand for the pattern
  2055.  
  2056.                 ` c ` | ` c1 ` | ` c2  ` |...| ` cn ` | ` d `
  2057.  
  2058.  
  2059. Chapter 3.   Language extensions                                            35
  2060.  
  2061.  
  2062. where c1,c2,...,cn  are the characters that occur between c and d in the
  2063. ASCII character set.  For instance, the pattern `0`..`9` matches all
  2064. characters that are digits.
  2065.  
  2066.  
  2067. 3.4 Recursive definitions of values
  2068.  
  2069. Besides let rec definitions of functional values, as described in the
  2070. reference manual, Caml Light supports a certain class of recursive definitions
  2071. of non-functional values.  For instance, the following definition is accepted:
  2072.  
  2073.         let rec x = 1 :: y and y = 2 :: x;;
  2074.  
  2075. and correctly binds x to the cyclic list 1::2::1::2::..., and y to the cyclic
  2076. list 2::1::2::1::...Informally, the class of accepted definitions consists of
  2077. those definitions where the defined variables occur only inside function
  2078. bodies or as a field of a data structure.  Moreover, the patterns in the
  2079. left-hand sides must be identifiers, nothing more complex.
  2080.  
  2081.  
  2082. 3.5 Local definitions using where
  2083.  
  2084. A postfix syntax for local definitions is provided:
  2085.  
  2086.                    expr  ::=  ...
  2087.                            |  expr where [rec] let-binding
  2088.  
  2089.  
  2090. The expression expr where let-binding behaves exactly as
  2091. let let-binding in expr, and similarly for where rec and let rec.
  2092.  
  2093.  
  2094. 3.6 Mutable variant types
  2095.  
  2096. The argument of a value constructor can be declared ``mutable'' when the
  2097. variant type is defined:
  2098.  
  2099.         type foo = A of mutable int
  2100.                  | B of mutable int * int
  2101.                  | ...
  2102.  
  2103. This allows in-place modification of the argument part of a constructed value.
  2104. Modification is performed by a new kind of expressions, written ident <- expr,
  2105. where ident is an identifier bound by pattern-matching to the argument of a
  2106. mutable constructor, and expr denotes the value that must be stored in place
  2107. of that argument.  Continuing the example above:
  2108.  
  2109.         let x = A 1 in
  2110.           begin match x with A y -> y <- 2 | _ -> () end;
  2111.           x
  2112.  
  2113. returns the value A 2.  The notation ident <- expr works also if ident is an
  2114. identifier bound by pattern-matching to the value of a mutable field in a
  2115. record.  For instance,
  2116.  
  2117.         type bar = {mutable lbl : int};;
  2118.         let x = {lbl = 1} in
  2119.           begin match x with {lbl = y} -> y <- 2 end;
  2120.           x
  2121.  
  2122.  
  2123. Chapter 3.   Language extensions                                            36
  2124.  
  2125.  
  2126. returns the value {lbl = 2}.
  2127.  
  2128.  
  2129. 3.7 String access
  2130.  
  2131. Extra syntactic constructs are provided to access and modify characters in
  2132. strings:
  2133.  
  2134.                       expr  ::=  ...
  2135.                               |  expr .[ expr ]
  2136.                               |  expr .[ expr ] <- expr
  2137.  
  2138.   The expression expr1 .[ expr2 ] is equivalent to the application
  2139. nth_char expr1 expr2.  In the initial environment, the identifier nth_char
  2140. resolves to a built-in function that returns the character number expr2 in
  2141. the string denoted by expr1.  The first element has number 0; the last
  2142. element has number n-1, where n is the length of the string.  The exception
  2143. Invalid_argument is raised if the access is out of bounds.
  2144.   The expression expr1 .[ expr2 ] <- expr3 is equivalent to
  2145. set_nth_char expr1 expr2 expr3.  In the initial environment, the identifier
  2146. set_nth_char resolves to a built-in function that modifies in-place the string
  2147. denoted by expr1, replacing character number expr2 by the value of expr3.
  2148. The exception Invalid_argument is raised if the access is out of bounds.  The
  2149. built-in function returns ().
  2150.  
  2151.  
  2152. 3.8 Alternate syntax
  2153.  
  2154. The syntax of some constructs has been slightly relaxed:
  2155.  
  2156.  -  An optional ; may terminate a sequence, list expression, or record
  2157.     expression.  For instance, begin e1 ; e2 ; end is syntactically correct
  2158.     and synonymous with begin e1 ; e2 end.
  2159.  
  2160.  -  Similarly, an optional | may begin a pattern-matching expression.  For
  2161.     instance, function | pat1 -> expr1 |... is syntactically correct and
  2162.     synonymous with function pat1 -> expr1 |....
  2163.  
  2164.  -  The tokens && and || are recognized as synonymous for & (sequential
  2165.     ``and'') and or (sequential ``or''), respectively.
  2166.  
  2167.  
  2168. 3.9 Infix symbols
  2169.  
  2170. Sequences of ``operator characters'', such as <=> or !!, are read as a single
  2171. token from the infix-symbol or prefix-symbol class:
  2172.  
  2173.  
  2174.  infix-symbol  ::=  (= | < | > | @ | ^ | | | & | ~ | + | - | * | / | $ | %) {operator-char}
  2175. prefix-symbol  ::=  (! | ?) {operator-char}
  2176. operator-char  ::=  ! | $ | % | & | * | + | - | . | / | : | ; | < | = | > | ? | @ | ^ | | | ~
  2177.  
  2178.  
  2179. Tokens from these two classes generalize the built-in infix and prefix
  2180. operators described in chapter 2:
  2181.  
  2182.  
  2183. Chapter 3.  Language extensions                                             37
  2184.  
  2185.  
  2186.                         expr  ::=  ...
  2187.                                 |  prefix-symbol expr
  2188.                                 |  expr infix-symbol expr
  2189.                     variable  ::=  ...
  2190.                                 |  prefix prefix-symbol
  2191.                                 |  prefix infix-symbol
  2192.  
  2193.  
  2194. No #infix directive (section 3.10) is needed to give infix symbols their infix
  2195. status.  The precedences and associativities of infix symbols in expressions
  2196. are determined by their first character(s):  symbols beginning with ** have
  2197. highest precedence (exponentiation), followed by symbols beginning with *, /
  2198. or % (multiplication), then + and - (addition), then all others symbols
  2199. (comparisons).  The updated precedence table for expressions is shown below.
  2200. We write ``*...''  to mean ``any infix symbol starting with *''.
  2201.     ----------------------------------------------------------------------
  2202.     |Construction or operator                             |Associativity |
  2203.     ----------------------------------------------------------------------
  2204.     |!...   ?...                                          |--            |
  2205.     |.   .(   .[                                          |--            |
  2206.     |function application                                 |right         |
  2207.     |constructor application                              |--            |
  2208.     |-   -.  (prefix)                                     |--            |
  2209.     |**...                                                |right         |
  2210.     |*...   /...   %...   mod                             |left          |
  2211.     |+...   -...                                          |left          |
  2212.     |::                                                   |right         |
  2213.     |@ ^                                                  |right         |
  2214.     |comparisons (=  ==  <  etc.), all other infix symbols|left          |
  2215.     |not                                                  |--            |
  2216.     |&   &&                                               |left          |
  2217.     |or  ||                                               |left          |
  2218.     |,                                                    |--            |
  2219.     |<-   :=                                              |right         |
  2220.     |if                                                   |--            |
  2221.     |;                                                    |right         |
  2222.     |let  match  fun  function  try                       |--            |
  2223.     ----------------------------------------------------------------------
  2224.  
  2225. Some infix and prefix symbols are predefined in the default environment (see
  2226. chapters 2 and 13 for a description of their behavior).  The others are
  2227. initially unbound and must be bound before use, with a
  2228. let prefix infix-symbol = expr or let prefix prefix-symbol = expr binding.
  2229.  
  2230.  
  2231. 3.10 Directives
  2232.  
  2233. In addition to the standard #open and #close directives, Caml Light provides
  2234. three additional directives.
  2235.  
  2236. #infix " id "
  2237.     Change the lexical status of the identifier id:  in the remainder of the
  2238.     compilation unit, id is recognized as an infix operator, just like +.
  2239.     The notation prefix id can be used to refer to the identifier id itself.
  2240.     Expressions of the form expr1 id expr2 are parsed as the application
  2241.     prefix id expr1 expr2.  The argument to the #infix directive must be an
  2242.     identifier, that is, a sequence of letters, digits and underscores
  2243.     starting with a letter; otherwise, the #infix declaration has no effect.
  2244.     Example:
  2245.  
  2246.  
  2247. Chapter 3.   Language extensions                                            38
  2248.  
  2249.  
  2250.             #infix "union";;
  2251.             let prefix union = fun x y -> ... ;;
  2252.             [1,2] union [3,4];;
  2253.  
  2254.  
  2255. #uninfix " id "
  2256.     Remove the infix status attached to the identifier id by a previous
  2257.     #infix " id " directive.
  2258.  
  2259. #directory " dir-name "
  2260.     Add the named directory to the path of directories searched for compiled
  2261.     module interface files.  This is equivalent to the -I command-line option
  2262.     to the batch compiler and the toplevel system.
  2263.  
  2264.  
  2265.  
  2266.  
  2267.  
  2268.  
  2269.  
  2270.  
  2271.  
  2272.  
  2273.  
  2274.  
  2275.  
  2276.  
  2277.  
  2278.  
  2279.  
  2280.  
  2281.  
  2282.  
  2283.  
  2284.  
  2285.  
  2286.  
  2287.                                    Part III
  2288.  
  2289.  
  2290.  
  2291.                            The Caml Light commands
  2292.  
  2293.  
  2294.  
  2295.  
  2296.  
  2297.  
  2298.  
  2299.  
  2300.  
  2301.  
  2302.  
  2303.  
  2304.  
  2305.  
  2306.  
  2307.  
  2308.  
  2309.  
  2310.  
  2311.  
  2312.  
  2313.  
  2314.  
  2315.  
  2316.  
  2317.  
  2318.  
  2319.  
  2320.  
  2321.  
  2322.  
  2323.  
  2324.  
  2325.  
  2326.  
  2327.  
  2328.                                       39
  2329.  
  2330.  
  2331.  
  2332.  
  2333.  
  2334.  
  2335.  
  2336.  
  2337.  
  2338.  
  2339.  
  2340. Chapter 4
  2341.  
  2342.  
  2343.  
  2344. Batch compilation (camlc)
  2345.  
  2346.  
  2347.  
  2348. This chapter describes how Caml Light programs can be compiled
  2349. non-interactively, and turned into standalone executable files.  This is
  2350. achieved by the command camlc, which compiles and links Caml Light source
  2351. files.
  2352.  
  2353. Mac:  This command is not a standalone Macintosh application.  To run camlc,
  2354.       you need the Macintosh Programmer's Workshop (MPW) programming
  2355.       environment.  The programs generated by camlc are also MPW tools, not
  2356.       standalone Macintosh applications.
  2357.  
  2358.  
  2359. 4.1 Overview of the compiler
  2360.  
  2361. The camlc command has a command-line interface similar to the one of most C
  2362. compilers.  It accepts several types of arguments:  source files for module
  2363. implementations; source files for module interfaces; and compiled module
  2364. implementations.
  2365.  
  2366.  -  Arguments ending in .mli are taken to be source files for module
  2367.     interfaces.  Module interfaces declare exported global identifiers,
  2368.     define public data types, and so on.  From the file x.mli, the camlc
  2369.     compiler produces a compiled interface in the file x.zi.
  2370.  
  2371.  -  Arguments ending in .ml are taken to be source files for module
  2372.     implementation.  Module implementations bind global identifiers to
  2373.     values, define private data types, and contain expressions to be
  2374.     evaluated for their side-effects.  From the file x.ml, the camlc compiler
  2375.     produces compiled object code in the file x.zo.  If the interface file
  2376.     x.mli exists, the module implementation x.ml is checked against the
  2377.     corresponding compiled interface x.zi, which is assumed to exist.  If no
  2378.     interface x.mli is provided, the compilation of x.ml produces a compiled
  2379.     interface file x.zi in addition to the compiled object code file x.zo.
  2380.     The file x.zi produced corresponds to an interface that exports
  2381.     everything that is defined in the implementation x.ml.
  2382.  
  2383.  -  Arguments ending in .zo are taken to be compiled object code.  These
  2384.     files are linked together, along with the object code files obtained by
  2385.     compiling .ml arguments (if any), and the Caml Light standard library, to
  2386.     produce a standalone executable program.  The order in which .zo and .ml
  2387.     arguments are presented on the command line is relevant:  global
  2388.     identifiers are initialized in that order at run-time, and it is a
  2389.     link-time error to use a global identifier before having initialized it.
  2390.     Hence, a given x.zo file must come before all .zo files that refer to
  2391.  
  2392.  
  2393.                                       40
  2394.  
  2395.  
  2396. Chapter 4.   Batch compilation (camlc)                                      41
  2397.  
  2398.  
  2399.     identifiers defined in the file x.zo.
  2400.  
  2401.   The output of the linking phase is a file containing compiled code that can
  2402. be executed by the Caml Light runtime system:  the command named camlrun.  If
  2403. caml.out is the name of the file produced by the linking phase, the command
  2404.  
  2405.         camlrun caml.out arg1 arg2 ... argn
  2406.  
  2407. executes the compiled code contained in caml.out, passing it as arguments the
  2408. character strings arg1 to argn.  (See chapter 6 for more details.)
  2409.  
  2410. Unix: On most Unix systems, the file produced by the linking phase can be run
  2411.       directly, as in:
  2412.  
  2413.  
  2414.               ./caml.out arg1 arg2 ... argn
  2415.  
  2416.  
  2417.       The produced file has the executable bit set, and it manages to launch
  2418.       the bytecode interpreter by itself.
  2419.  
  2420. PC:   The output file produced by the linking phase is directly executable,
  2421.       provided it is given extension .EXE. Hence, if the output file is named
  2422.       caml_out.exe, you can execute it with the command
  2423.  
  2424.  
  2425.               caml_out arg1 arg2 ... argn
  2426.  
  2427.  
  2428.       Actually, the produced file caml_out.exe is a tiny executable file
  2429.       prepended to the bytecode file.  The executable simply runs the camlrun
  2430.       runtime system on the remainder of the file.  (As a consequence, this
  2431.       is not a standalone executable:  it still requires camlrun.exe to
  2432.       reside in one of the directories in the path.)
  2433.  
  2434.  
  2435. 4.2 Options
  2436.  
  2437. The following command-line options are recognized by camlc.
  2438.  
  2439. -c  Compile only.  Suppress the linking phase of the compilation.  Source
  2440.     code files are turned into compiled files, but no executable file is
  2441.     produced.  This option is useful to compile modules separately.
  2442.  
  2443. -ccopt option
  2444.     Pass the given option to the C compiler and linker, when linking in
  2445.     ``custom runtime'' mode (see the -custom option).  For instance, -ccopt
  2446.     -Ldir causes the C linker to search for C libraries in directory dir.
  2447.  
  2448. -custom
  2449.     Link in ``custom runtime'' mode.  In the default linking mode, the linker
  2450.     produces bytecode that is intended to be executed with the shared runtime
  2451.     system, camlrun.  In the custom runtime mode, the linker produces an
  2452.     output file that contains both the runtime system and the bytecode for
  2453.     the program.  The resulting file is considerably larger, but it can be
  2454.     executed directly, even if the camlrun command is not installed.
  2455.     Moreover, the ``custom runtime'' mode enables linking Caml Light code
  2456.     with user-defined C functions, as described in chapter 12.
  2457.  
  2458.  
  2459. Chapter 4.   Batch compilation (camlc)                                      42
  2460.  
  2461.  
  2462.     Unix: Never strip an executable produced with the -custom option.
  2463.  
  2464.  
  2465.     PC:   This option requires the DJGPP port of the GNU C compiler to be
  2466.           installed.
  2467.  
  2468.  
  2469. -files response-file
  2470.     Process the files whose names are listed in file response-file, just as
  2471.     if these names appeared on the command line.  File names in response-file
  2472.     are separated by blanks (spaces, tabs, newlines).  This option allows to
  2473.     overcome silly limitations on the length of the command line.
  2474.  
  2475. -g  Cause the compiler to produce additional debugging information.  During
  2476.     the linking phase, this option add information at the end of the
  2477.     executable bytecode file produced.  This information is required by the
  2478.     debugger camldebug and also by the catch-all exception handler from the
  2479.     standard library module printexc.
  2480.  
  2481.     During the compilation of an implementation file (.ml file), when the -g
  2482.     option is set, the compiler adds debugging information to the .zo file.
  2483.     It also writes a .zix file that describes the full interface of the .ml
  2484.     file, that is, all types and values defined in the .ml file, including
  2485.     those that are local to the .ml file (i.e.  not declared in the .mli
  2486.     interface file).  Used in conjunction with the -g option to the toplevel
  2487.     system (chapter 5), the .zix file gives access to the local values of the
  2488.     module, making it possible to print or ``trace'' them.  The .zix file is
  2489.     not produced if the implementation file has no explicit interface, since,
  2490.     in this case, the module has no local values.
  2491.  
  2492. -i  Cause the compiler to print the declared types, exceptions, and global
  2493.     variables (with their inferred types) when compiling an implementation
  2494.     (.ml file).  This can be useful to check the types inferred by the
  2495.     compiler.  Also, since the output follows the syntax of module
  2496.     interfaces, it can help in writing an explicit interface (.mli file) for
  2497.     a file:  just redirect the standard output of the compiler to a .mli
  2498.     file, and edit that file to remove all declarations of unexported
  2499.     globals.
  2500.  
  2501. -I directory
  2502.     Add the given directory to the list of directories searched for compiled
  2503.     interface files (.zi) and compiled object code files (.zo).  By default,
  2504.     the current directory is searched first, then the standard library
  2505.     directory.  Directories added with -I are searched after the current
  2506.     directory, but before the standard library directory.  When several
  2507.     directories are added with several -I options on the command line, these
  2508.     directories are searched from right to left (the rightmost directory is
  2509.     searched first, the leftmost is searched last).  (Directories can also be
  2510.     added to the search path from inside the programs with the #directory
  2511.     directive; see chapter 3.)
  2512.  
  2513. -lang language-code
  2514.     Translate the compiler messages to the specified language.  The
  2515.     language-code is fr for French, es for Spanish, de for German, ... (See
  2516.     the file camlmsgs.txt in the Caml Light standard library directory for a
  2517.     list of available languages.)  When an unknown language is specified, or
  2518.     no translation is available for a message, American English is used by
  2519.     default.
  2520.  
  2521.  
  2522. Chapter 4.   Batch compilation (camlc)                                      43
  2523.  
  2524.  
  2525. -o exec-file
  2526.     Specify the name of the output file produced by the linker.
  2527.  
  2528.  
  2529.     Unix: The default output name is a.out, in keeping with the tradition.
  2530.  
  2531.  
  2532.     PC:   The default output name is caml_out.exe.
  2533.  
  2534.  
  2535.     Mac:  The default output name is Caml.Out.
  2536.  
  2537.  
  2538. -O module-set
  2539.     Specify which set of standard modules is to be implicitly ``opened'' at
  2540.     the beginning of a compilation.  There are three module sets currently
  2541.     available:
  2542.  
  2543.  
  2544.      cautious
  2545.         provides the standard operations on integers, floating-point numbers,
  2546.         characters, strings, arrays, ..., as well as exception handling,
  2547.         basic input/output, etc.  Operations from the cautious set perform
  2548.         range and bound checking on string and array operations, as well as
  2549.         various sanity checks on their arguments.
  2550.  
  2551.      fast
  2552.         provides the same operations as the cautious set, but without sanity
  2553.         checks on their arguments.  Programs compiled with -O fast are
  2554.         therefore slightly faster, but unsafe.
  2555.  
  2556.      none
  2557.         suppresses all automatic opening of modules.  Compilation starts in
  2558.         an almost empty environment.  This option is not of general use,
  2559.         except to compile the standard library itself.
  2560.  
  2561.  
  2562.     The default compilation mode is -O cautious.  See chapter 13 for a
  2563.     complete listing of the modules in the cautious and fast sets.
  2564.  
  2565. -p  Compile and link in profiling mode.  See the description of the profiler
  2566.     camlpro in chapter 10.
  2567.  
  2568. -v  Print the version number of the compiler.
  2569.  
  2570. -W  Print extra warning messages for the following events:
  2571.  
  2572.  
  2573.      -  A #open directive is useless (no identifier in the opened module is
  2574.         ever referenced).
  2575.  
  2576.      -  A variable name in a pattern matching is capitalized (often
  2577.         corresponds to a misspelled constant constructor).
  2578.  
  2579.  
  2580. Unix: The following environment variable is also consulted:
  2581.  
  2582.  
  2583. Chapter 4.   Batch compilation (camlc)                                      44
  2584.  
  2585.  
  2586.       LANGWhen set, control which language is used to print the compiler
  2587.           messages (see the -lang command-line option).
  2588.  
  2589.  
  2590. PC:   The following environment variables are also consulted:
  2591.  
  2592.  
  2593.       CAMLLIB
  2594.           Contain the path to the standard library directory.
  2595.  
  2596.       LANGWhen set, control which language is used to print the compiler
  2597.           messages (see the -lang command-line option).
  2598.  
  2599.  
  2600.  
  2601. 4.3 Modules and the file system
  2602.  
  2603. This short section is intended to clarify the relationship between the names
  2604. of the modules and the names of the files that contain their compiled
  2605. interface and compiled implementation.
  2606.   The compiler always derives the name of the compiled module by taking the
  2607. base name of the source file (.ml or .mli file).  That is, it strips the
  2608. leading directory name, if any, as well as the .ml or .mli suffix.  The
  2609. produced .zi and .zo files have the same base name as the source file; hence,
  2610. the compiled files produced by the compiler always have their base name equal
  2611. to the name of the module they describe (for .zi files) or implement (for .zo
  2612. files).
  2613.   For compiled interface files (.zi files), this invariant must be preserved
  2614. at all times, since the compiler relies on it to load the compiled interface
  2615. file for the modules that are used from the module being compiled.  Hence, it
  2616. is risky and generally incorrect to rename .zi files.  It is admissible to
  2617. move them to another directory, if their base name is preserved, and the
  2618. correct -I options are given to the compiler.
  2619.   Compiled bytecode files (.zo files), on the other hand, can be freely
  2620. renamed once created.  That's because 1- .zo files contain the true name of
  2621. the module they define, so there is no need to derive that name from the file
  2622. name; 2- the linker never attempts to find by itself the .zo file that
  2623. implements a module of a given name:  it relies on the user providing the list
  2624. of .zo files by hand.
  2625.  
  2626.  
  2627. 4.4 Common errors
  2628.  
  2629. This section describes and explains the most frequently encountered error
  2630. messages.
  2631.  
  2632. Cannot find file filename
  2633.     The named file could not be found in the current directory, nor in the
  2634.     directories of the search path.  The filename is either a compiled
  2635.     interface file (.zi file), or a compiled bytecode file (.zo file).  If
  2636.     filename has the format mod.zi, this means you are trying to compile a
  2637.     file that references identifiers from module mod, but you have not yet
  2638.     compiled an interface for module mod.  Fix:  compile mod.mli or mod.ml
  2639.     first, to create the compiled interface mod.zi.
  2640.  
  2641.     If filename has the format mod.zo, this means you are trying to link a
  2642.     bytecode object file that does not exist yet.  Fix:  compile mod.ml
  2643.     first.
  2644.  
  2645.  
  2646. Chapter 4.   Batch compilation (camlc)                                      45
  2647.  
  2648.  
  2649.     If your program spans several directories, this error can also appear
  2650.     because you haven't specified the directories to look into.  Fix:  add
  2651.     the correct -I options to the command line.
  2652.  
  2653. Corrupted compiled interface file filename
  2654.     The compiler produces this error when it tries to read a compiled
  2655.     interface file (.zi file) that has the wrong structure.  This means
  2656.     something went wrong when this .zi file was written:  the disk was full,
  2657.     the compiler was interrupted in the middle of the file creation, and so
  2658.     on.  This error can also appear if a .zi file is modified after its
  2659.     creation by the compiler.  Fix:  remove the corrupted .zi file, and
  2660.     rebuild it.
  2661.  
  2662. This expression has type t1, but is used with type t2
  2663.     This is by far the most common type error in programs.  Type t1 is the
  2664.     type inferred for the expression (the part of the program that is
  2665.     displayed in the error message), by looking at the expression itself.
  2666.     Type t2 is the type expected by the context of the expression; it is
  2667.     deduced by looking at how the value of this expression is used in the
  2668.     rest of the program.  If the two types t1 and t2 are not compatible, then
  2669.     the error above is produced.
  2670.  
  2671.     In some cases, it is hard to understand why the two types t1 and t2 are
  2672.     incompatible.  For instance, the compiler can report that ``expression of
  2673.     type foo cannot be used with type foo'', and it really seems that the two
  2674.     types foo are compatible.  This is not always true.  Two type
  2675.     constructors can have the same name, but actually represent different
  2676.     types.  This can happen if a type constructor is redefined.  Example:
  2677.  
  2678.  
  2679.             type foo = A | B;;
  2680.             let f = function A -> 0 | B -> 1;;
  2681.             type foo = C | D;;
  2682.             f C;;
  2683.  
  2684.  
  2685.     This result in the error message ``expression C of type foo cannot be
  2686.     used with type foo''.
  2687.  
  2688.     Incompatible types with the same names can also appear when a module is
  2689.     changed and recompiled, but some of its clients are not recompiled.
  2690.     That's because type constructors in .zi files are not represented by
  2691.     their name (that would not suffice to identify them, because of type
  2692.     redefinitions), but by unique stamps that are assigned when the type
  2693.     declaration is compiled.  Consider the three modules:
  2694.  
  2695.  
  2696.             mod1.ml:    type t = A | B;;
  2697.                         let f = function A -> 0 | B -> 1;;
  2698.  
  2699.             mod2.ml:    let g x = 1 + mod1__f(x);;
  2700.  
  2701.             mod3.ml:    mod2__g mod1__A;;
  2702.  
  2703.  
  2704.     Now, assume mod1.ml is changed and recompiled, but mod2.ml is not
  2705.     recompiled.  The recompilation of mod1.ml can change the stamp assigned
  2706.     to type t.  But the interface mod2.zi will still use the old stamp for
  2707.  
  2708.  
  2709. Chapter 4.   Batch compilation (camlc)                                      46
  2710.  
  2711.  
  2712.     mod1__t in the type of mod2__g.  Hence, when compiling mod3.ml, the
  2713.     system complains that the argument type of mod2__g (that is, mod1__t with
  2714.     the old stamp) is not compatible with the type of mod1__A (that is,
  2715.     mod1__t with the new stamp).  Fix:  use make or a similar tool to ensure
  2716.     that all clients of a module mod are recompiled when the interface mod.zi
  2717.     changes.  To check that the Makefile contains the right dependencies,
  2718.     remove all .zi files and rebuild the whole program; if no ``Cannot find
  2719.     file'' error appears, you're all set.
  2720.  
  2721.  
  2722. The type inferred for name, that is, t, contains non-generalizable type variables
  2723.  
  2724.     Type variables ('a, 'b, ...)  in a type t can be in either of two states:
  2725.     generalized (which means that the type t is valid for all possible
  2726.     instantiations of the variables) and not generalized (which means that
  2727.     the type t is valid only for one instantiation of the variables).  In a
  2728.     let binding let name = expr, the type-checker normally generalizes as
  2729.     many type variables as possible in the type of expr.  However, this leads
  2730.     to unsoundness (a well-typed program can crash) in conjunction with
  2731.     polymorphic mutable data structures.  To avoid this, generalization is
  2732.     performed at let bindings only if the bound expression expr belongs to
  2733.     the class of ``syntactic values'', which includes constants, identifiers,
  2734.     functions, tuples of syntactic values, etc.  In all other cases (for
  2735.     instance, expr is a function application), a polymorphic mutable could
  2736.     have been created and generalization is therefore turned off.
  2737.  
  2738.     Non-generalized type variables in a type cause no difficulties inside a
  2739.     given compilation unit (the contents of a .ml file, or an interactive
  2740.     session), but they cannot be allowed in types written in a .zi compiled
  2741.     interface file, because they could be used inconsistently in other
  2742.     compilation units.  Therefore, the compiler flags an error when a .ml
  2743.     implementation without a .mli interface defines a global variable name
  2744.     whose type contains non-generalized type variables.  There are two
  2745.     solutions to this problem:
  2746.  
  2747.  
  2748.      -  Add a type constraint or a .mli interface to give a monomorphic type
  2749.         (without type variables) to name.  For instance, instead of writing
  2750.  
  2751.  
  2752.             let sort_int_list = sort (prefix <);;
  2753.             (* inferred type 'a list -> 'a list, with 'a not generalized *)
  2754.  
  2755.  
  2756.         write
  2757.  
  2758.  
  2759.             let sort_int_list = (sort (prefix <) : int list -> int list);;
  2760.  
  2761.  
  2762.      -  If you really need name to have a polymorphic type, turn its defining
  2763.         expression into a function by adding an extra parameter.  For
  2764.         instance, instead of writing
  2765.  
  2766.  
  2767.             let map_length = map vect_length;;
  2768.             (*  inferred type 'a vect list ->  int list, with 'a not  general-
  2769.         ized *)
  2770.  
  2771.  
  2772. Chapter 4.   Batch compilation (camlc)                                      47
  2773.  
  2774.  
  2775.         write
  2776.  
  2777.  
  2778.                 let map_length lv = map vect_length lv;;
  2779.  
  2780.  
  2781. mod__name is referenced before being defined
  2782.     This error appears when trying to link an incomplete or incorrectly
  2783.     ordered set of files.  Either you have forgotten to provide an
  2784.     implementation for the module named mod on the command line (typically,
  2785.     the file named mod.zo, or a library containing that file).  Fix:  add the
  2786.     missing .ml or .zo file to the command line.  Or, you have provided an
  2787.     implementation for the module named mod, but it comes too late on the
  2788.     command line:  the implementation of mod must come before all bytecode
  2789.     object files that reference one of the global variables defined in module
  2790.     mod.  Fix:  change the order of .ml and .zo files on the command line.
  2791.  
  2792.     Of course, you will always encounter this error if you have mutually
  2793.     recursive functions across modules.  That is, function mod1__f calls
  2794.     function mod2__g, and function mod2__g calls function mod1__f.  In this
  2795.     case, no matter what permutations you perform on the command line, the
  2796.     program will be rejected at link-time.  Fixes:
  2797.  
  2798.  
  2799.      -  Put f and g in the same module.
  2800.  
  2801.      -  Parameterize one function by the other.  That is, instead of having
  2802.  
  2803.  
  2804.         mod1.ml:    let f x = ... mod2__g ... ;;
  2805.         mod2.ml:    let g y = ... mod1__f ... ;;
  2806.  
  2807.  
  2808.         define
  2809.  
  2810.  
  2811.         mod1.ml:    let f g x = ... g ... ;;
  2812.         mod2.ml:    let rec g y = ... mod1__f g ... ;;
  2813.  
  2814.  
  2815.         and link mod1 before mod2.
  2816.  
  2817.      -  Use a reference to hold one of the two functions, as in :
  2818.  
  2819.  
  2820.         mod1.ml:    let forward_g =
  2821.                         ref((fun x -> failwith "forward_g") : <type>);;
  2822.                     let f x = ... !forward_g ... ;;
  2823.         mod2.ml:    let g y = ... mod1__f ... ;;
  2824.                     mod1__forward_g := g;;
  2825.  
  2826.  
  2827. Unavailable C primitive f
  2828.     This error appears when trying to link code that calls external functions
  2829.     written in C in ``default runtime'' mode.  As explained in chapter 12,
  2830.     such code must be linked in ``custom runtime'' mode.  Fix:  add the
  2831.     -custom option, as well as the (native code) libraries and (native code)
  2832.     object files that implement the required external functions.
  2833.  
  2834.  
  2835.  
  2836.  
  2837.  
  2838.  
  2839.  
  2840.  
  2841.  
  2842.  
  2843.  
  2844. Chapter 5
  2845.  
  2846.  
  2847.  
  2848. The toplevel system (camllight)
  2849.  
  2850.  
  2851.  
  2852. This chapter describes the toplevel system for Caml Light, that permits
  2853. interactive use of the Caml Light system, through a read-eval-print loop.  In
  2854. this mode, the system repeatedly reads Caml Light phrases from the input, then
  2855. typechecks, compile and evaluate them, then prints the inferred type and
  2856. result value, if any.  The system prints a # (sharp) prompt before reading
  2857. each phrase.  A phrase can span several lines.  Phrases are delimited by ;;
  2858. (the final double-semicolon).
  2859.   From the standpoint of the module system, all phrases entered at toplevel
  2860. are treated as the implementation of a module named top.  Hence, all toplevel
  2861. definitions are entered in the module top.
  2862.  
  2863. Unix: The toplevel system is started by the command camllight.  Phrases are
  2864.       read on standard input, results are printed on standard output, errors
  2865.       on standard error.  End-of-file on standard input terminates camllight
  2866.       (see also the quit system function below).
  2867.  
  2868.       The toplevel system does not perform line editing, but it can easily be
  2869.       used in conjunction with an external line editor such as fep; just run
  2870.       fep -emacs camllight or fep -vi camllight.  Another option is to use
  2871.       camllight under Gnu Emacs, which gives the full editing power of Emacs
  2872.       (see the directory contrib/camlmode in the distribution).
  2873.  
  2874.       At any point, the parsing, compilation or evaluation of the current
  2875.       phrase can be interrupted by pressing ctrl-C (or, more precisely, by
  2876.       sending the intr signal to the camllight process).  This goes back to
  2877.       the # prompt.
  2878.  
  2879. Mac:  The toplevel system is presented as the standalone Macintosh
  2880.       application Caml Light.  This application does not require the
  2881.       Macintosh Programmer's Workshop to run.
  2882.  
  2883.       Once launched from the Finder, the application opens two windows,
  2884.       ``Caml Light Input'' and ``Caml Light Output''.  Phrases are entered in
  2885.       the ``Caml Light Input'' window.  The ``Caml Light Output'' window
  2886.       displays a copy of the input phrases as they are processed by the Caml
  2887.       Light toplevel, interspersed with the toplevel responses.  The
  2888.       ``Return'' key sends the contents of the Input window to the Caml Light
  2889.       toplevel.  The ``Enter'' key inserts a newline without sending the
  2890.       contents of the Input window.  (This can be configured with the
  2891.       ``Preferences'' menu item.)
  2892.  
  2893.       The contents of the input window can be edited at all times, with the
  2894.       standard Macintosh interface.  An history of previously entered phrases
  2895.  
  2896.  
  2897.                                       48
  2898.  
  2899.  
  2900. Chapter 5.   The toplevel system (camllight)                                49
  2901.  
  2902.  
  2903.       is maintained, and can be accessed with the ``Previous entry''
  2904.       (command-P) and ``Next entry'' (command-N) menu items.
  2905.  
  2906.       To quit the Caml Light application, either select ``Quit'' from the
  2907.       ``Files'' menu, or use the quit function described below.
  2908.  
  2909.       At any point, the parsing, compilation or evaluation of the current
  2910.       phrase can be interrupted by pressing ``command-period'', or by
  2911.       selecting the item ``Interrupt Caml Light'' in the ``Caml Light'' menu.
  2912.       This goes back to the # prompt.
  2913.  
  2914. PC:   The toplevel system is started by the command caml.  (The full name
  2915.       camllight had to be truncated because of the well-known limitations of
  2916.       MS-DOS.) Phrases are read on standard input, results are printed on
  2917.       standard output, errors on standard error.  The quit system function
  2918.       terminates caml.
  2919.  
  2920.       A number of TSR line editors that provide line editing and history
  2921.       facilities for the command.com command-line interpreter also work in
  2922.       conjunction with caml.  Some TSR's that work:  dosedit, ced, toddy.
  2923.       Some TSR's that don't work:  doskey from the MS-DOS distribution.
  2924.  
  2925.       At any point, the parsing, compilation or evaluation of the current
  2926.       phrase can be interrupted by pressing ctrl-break or ctrl-C. This goes
  2927.       back to the # prompt.
  2928.  
  2929.  
  2930. 5.1 Options
  2931.  
  2932. The following command-line options are recognized by the caml or camllight
  2933. commands.
  2934.  
  2935. -g  Start the toplevel system in debugging mode.  This mode gives access to
  2936.     values and types that are local to a module, that is, not exported by the
  2937.     interface of the module.  When debugging mode is off, these local objects
  2938.     are not accessible (attempts to access them produce an ``Unbound
  2939.     identifier'' error).  When debugging mode is on, these objects become
  2940.     visible, just like the objects that are exported in the module interface.
  2941.     In particular, values of abstract types are printed using their concrete
  2942.     representations, and the functions local to a module can be ``traced''
  2943.     (see the trace function in section 5.2).  This applies only to the
  2944.     modules that have been compiled in debugging mode (either by the batch
  2945.     compiler with the -g option, or by the toplevel system in debugging
  2946.     mode), that is, those modules that have an associated .zix file.
  2947.  
  2948. -I directory
  2949.     Add the given directory to the list of directories searched for compiled
  2950.     interface files (.zi) and compiled object code files (.zo).  By default,
  2951.     the current directory is searched first, then the standard library
  2952.     directory.  Directories added with -I are searched after the current
  2953.     directory, but before the standard library directory.  When several
  2954.     directories are added with several -I options on the command line, these
  2955.     directories are searched from right to left (the rightmost directory is
  2956.     searched first, the leftmost is searched last).  Directories can also be
  2957.     added to the search path once the toplevel is running with the #directory
  2958.     directive; see chapter 3.
  2959.  
  2960.  
  2961. Chapter 5.   The toplevel system (camllight)                                50
  2962.  
  2963.  
  2964. -lang language-code
  2965.     Translate the toplevel messages to the specified language.  The
  2966.     language-code is fr for French, es for Spanish, de for German, ... (See
  2967.     the file camlmsgs.txt in the Caml Light standard library directory for a
  2968.     list of available languages.)  When an unknown language is specified, or
  2969.     no translation is available for a message, American English is used by
  2970.     default.
  2971.  
  2972. -O module-set
  2973.     Specify which set of standard modules is to be implicitly ``opened'' when
  2974.     the toplevel starts.  There are three module sets currently available:
  2975.  
  2976.  
  2977.     cautious
  2978.         provides the standard operations on integers, floating-point numbers,
  2979.         characters, strings, arrays, ..., as well as exception handling,
  2980.         basic input/output, ...Operations from the cautious set perform range
  2981.         and bound checking on string and vector operations, as well as
  2982.         various sanity checks on their arguments.
  2983.  
  2984.     fast
  2985.         provides the same operations as the cautious set, but without sanity
  2986.         checks on their arguments.  Programs compiled with -O fast are
  2987.         therefore slightly faster, but unsafe.
  2988.  
  2989.     none
  2990.         suppresses all automatic opening of modules.  Compilation starts in
  2991.         an almost empty environment.  This option is not of general use.
  2992.  
  2993.  
  2994.     The default compilation mode is -O cautious.  See chapter 13 for a
  2995.     complete listing of the modules in the cautious and fast sets.
  2996.  
  2997. Unix: The following environment variables are also consulted:
  2998.  
  2999.  
  3000.       LANGWhen set, control which language is used to print the compiler
  3001.           messages (see the -lang command-line option).
  3002.  
  3003.       LC_CTYPE
  3004.           If set to iso_8859_1, accented characters (from the ISO Latin-1
  3005.           character set) in string and character literals are printed as is;
  3006.           otherwise, they are printed as decimal escape sequences (\ddd).
  3007.  
  3008.  
  3009. PC:   The following environment variables are also consulted:
  3010.  
  3011.  
  3012.       CAMLLIB
  3013.           Contain the path to the standard library directory.
  3014.  
  3015.       LANGWhen set, control which language is used to print the compiler
  3016.           messages (see the -lang command-line option).
  3017.  
  3018.  
  3019. Chapter 5.   The toplevel system (camllight)                                51
  3020.  
  3021.  
  3022. 5.2 Toplevel control functions
  3023.  
  3024. The standard library module toplevel, opened by default when the toplevel
  3025. system is launched, provides a number of functions that control the toplevel
  3026. behavior, load files in memory, and trace program execution.
  3027.  
  3028.  
  3029. value quit : unit -> unit
  3030.  
  3031.     Exit the toplevel loop and terminate the camllight command.
  3032.  
  3033. value include : string -> unit
  3034.  
  3035.     Read, compile and execute source phrases from the given file.  The .ml
  3036.     extension is automatically added to the file name, if not present.  This
  3037.     is textual inclusion:  phrases are processed just as if they were typed
  3038.     on standard input.  In particular, global identifiers defined by these
  3039.     phrases are entered in the module named top, not in a new module.
  3040.  
  3041. value load : string -> unit
  3042.  
  3043.     Load in memory the source code for a module implementation.  Read,
  3044.     compile and execute source phrases from the given file.  The .ml
  3045.     extension is automatically added if not present.  The load function
  3046.     behaves much like include, except that a new module is created, with name
  3047.     the base name of the source file name.  Global identifiers defined in the
  3048.     source file are entered in this module, instead of the top module as in
  3049.     the case of include.  For instance, assuming file foo.ml contains the
  3050.     single phrase
  3051.  
  3052.  
  3053.                let bar = 1;;
  3054.  
  3055.  
  3056.     executing load "foo" defines the identifier foo__bar with value 1.
  3057.     Caveat:  the loaded module is not automatically opened:  the identifier
  3058.     bar does not automatically complete to foo__bar.  To achieve this, you
  3059.     must execute the directive #open "foo" afterwards.
  3060.  
  3061. value compile : string -> unit
  3062.  
  3063.     Compile the source code for a module implementation or interface (.ml or
  3064.     .mli file).  Compilation proceeds as with the batch compiler, and
  3065.     produces the same results as camlc -c.  If the toplevel system is in
  3066.     debugging mode (option -g or function debug_mode below), the compilation
  3067.     is also performed in debugging mode, as when giving the -g option to the
  3068.     batch compiler.  The result of the compilation is left in files (.zo,
  3069.     .zi, .zix).  The compiled code is not loaded in memory.  Use load_object
  3070.     to load a .zo file produced by compile.
  3071.  
  3072. value load_object : string -> unit
  3073.  
  3074.     Load in memory the compiled bytecode contained in the given file.  The
  3075.     .zo extension is automatically added to the file name, if not present.
  3076.     The bytecode file has been produced either by the standalone compiler
  3077.     camlc or by the compile function.  Global identifiers defined in the file
  3078.     being loaded are entered in their own module, not in the top module, just
  3079.     as with the load function.
  3080.  
  3081.  
  3082. Chapter 5.   The toplevel system (camllight)                                52
  3083.  
  3084.  
  3085. value trace : string -> unit
  3086.  
  3087.     After the execution of trace "foo", all calls to the global function
  3088.     named foo will be ``traced''.  That is, the argument and the result are
  3089.     displayed for each call, as well as the exceptions escaping out of foo,
  3090.     either raised by foo itself, or raised by one of the functions called
  3091.     from foo.  If foo is a curried function, each argument is printed as it
  3092.     is passed to the function.  Only functions implemented in ML can be
  3093.     traced; system primitives such as string_length or user-supplied C
  3094.     functions cannot.
  3095.  
  3096. value untrace : string -> unit
  3097.  
  3098.     Executing untrace "foo" stops all tracing over the global function named
  3099.     foo.
  3100.  
  3101. value verbose_mode: bool -> unit
  3102.  
  3103.     verbose_mode true causes the compile function to print the inferred types
  3104.     and other information.  verbose_mode false reverts to the default silent
  3105.     behavior.
  3106.  
  3107. value install_printer : string -> unit
  3108.  
  3109.     install_printer "printername" registers the function named printername as
  3110.     a printer for objects whose types match its argument type.  That is, the
  3111.     toplevel loop will call printername when it has such an object to print.
  3112.     The printing function printername must use the format library module to
  3113.     produce its output, otherwise the output of printername will not be
  3114.     correctly located in the values printed by the toplevel loop.
  3115.  
  3116. value remove_printer : string -> unit
  3117.  
  3118.     remove_printer "printername" removes the function named printername from
  3119.     the table of toplevel printers.
  3120.  
  3121. value set_print_depth : int -> unit
  3122.  
  3123.     set_print_depth n limits the printing of values to a maximal depth of n.
  3124.     The parts of values whose depth exceeds n are printed as ... (ellipsis).
  3125.  
  3126. value set_print_length : int -> unit
  3127.  
  3128.     set_print_length n limits the number of value nodes printed to at most n.
  3129.     Remaining parts of values are printed as ... (ellipsis).
  3130.  
  3131. value debug_mode: bool -> unit
  3132.  
  3133.     Set whether extended module interfaces must be used debug_mode true or
  3134.     not debug_mode false.  Extended module interfaces are .zix files that
  3135.     describe the actual implementation of a module, including private types
  3136.     and variables.  They are generated when compiling with camlc -g, or with
  3137.     the compile function above when debug_mode is true.  When debug_mode is
  3138.     true, toplevel phrases can refer to private types and variables of
  3139.     modules, and private functions can be traced with trace.  Setting
  3140.     debug_mode true is equivalent to starting the toplevel with the -g
  3141.     option.
  3142.  
  3143.  
  3144. Chapter 5.  The toplevel system (camllight)                                 53
  3145.  
  3146.  
  3147. value cd : string -> unit
  3148.  
  3149.     Change the current working directory.
  3150.  
  3151. value directory : string -> unit
  3152.  
  3153.     Add the given directory to the search path for files.  Same behavior as
  3154.     the -I option or the #directory directive.
  3155.  
  3156.  
  3157.  
  3158. 5.3 The toplevel and the module system
  3159.  
  3160. Toplevel phrases can refer to identifiers defined in modules other than the
  3161. top module with the same mechanisms as for separately compiled modules:
  3162. either by using qualified identifiers (modulename__localname), or by using
  3163. unqualified identifiers that are automatically completed by searching the list
  3164. of opened modules.  (See section 2.2.)  The modules opened at startup are
  3165. given in the documentation for the standard library.  Other modules can be
  3166. opened with the #open directive.
  3167.   However, before referencing a global variable from a module other than the
  3168. top module, a definition of that global variable must have been entered in
  3169. memory.  At start-up, the toplevel system contains the definitions for all the
  3170. identifiers in the standard library.  The definitions for user modules can be
  3171. entered with the load or load_object functions described above.  Referencing a
  3172. global variable for which no definition has been provided by load or
  3173. load_object results in the error ``Identifier foo__bar is referenced before
  3174. being defined''.  Since this is a tricky point, let us consider some examples.
  3175.  
  3176. 1.  The library function sub_string is defined in module string.  This module
  3177.     is part of the standard library, and is one of the modules automatically
  3178.     opened at start-up.  Hence, both phrases
  3179.  
  3180.  
  3181.             sub_string "qwerty" 1 3;;
  3182.             string__sub_string "qwerty" 1 3;;
  3183.  
  3184.  
  3185.     are correct, without having to use #open, load, or load_object.
  3186.  
  3187. 2.  The library function printf is defined in module printf.  This module is
  3188.     part of the standard library, but it is not automatically opened at
  3189.     start-up.  Hence, the phrase
  3190.  
  3191.  
  3192.             printf__printf "%s %s" "hello" "world";;
  3193.  
  3194.  
  3195.     is correctly executed, while
  3196.  
  3197.  
  3198.             printf "%s %s" "hello" "world";;
  3199.  
  3200.  
  3201.     causes the error ``Variable printf is unbound'', since none of the
  3202.     currently opened modules define a global with local name printf.
  3203.     However,
  3204.  
  3205.  
  3206. Chapter 5.   The toplevel system (camllight)                                54
  3207.  
  3208.  
  3209.             #open "printf";;
  3210.             printf "%s %s" "hello" "world";;
  3211.  
  3212.  
  3213.     executes correctly.
  3214.  
  3215. 3.  Assume the file foo.ml resides in the current directory, and contains the
  3216.     single phrase
  3217.  
  3218.  
  3219.             let x = 1;;
  3220.  
  3221.  
  3222.     When the toplevel starts, references to x will cause the error ``Variable
  3223.     x is unbound''.  References to foo__x will cause the error ``Cannot find
  3224.     file foo.zi'', since the typechecker is attempting to load the compiled
  3225.     interface for module foo in order to find the type of x.  To load in
  3226.     memory the module foo, just do:
  3227.  
  3228.  
  3229.             load "foo";;
  3230.  
  3231.  
  3232.     Then, references to foo__x typecheck and evaluate correctly.  Since load
  3233.     does not open the module it loads, references to x will still fail with
  3234.     the error ``Variable x is unbound''.  You will have to do
  3235.  
  3236.  
  3237.             #open "foo";;
  3238.  
  3239.  
  3240.     explicitly, for x to complete automatically into foo__x.
  3241.  
  3242. 4.  Finally, assume the file foo.ml above has been previously compiled with
  3243.     the camlc -c command.  The current directory therefore contains a
  3244.     compiled interface foo.zi, claiming that foo__x is a global variable with
  3245.     type int, and a compiled bytecode file foo.zo, defining foo__x to have
  3246.     the value 1.  When the toplevel starts, references to foo__x will cause
  3247.     the error ``foo__x is referenced before being defined''.  In contrast
  3248.     with case 3 above, the typechecker has succeeded in finding the compiled
  3249.     interface for module foo.  But execution cannot proceed, because no
  3250.     definition for foo__x has been entered in memory.  To do so, execute:
  3251.  
  3252.  
  3253.             load_object "foo";;
  3254.  
  3255.  
  3256.     This loads the file foo.zo in memory, therefore defining foo__x.  Then,
  3257.     references to foo__x evaluate correctly.  As in case 3 above, references
  3258.     to x still fail, because load_object does not open the module it loads.
  3259.     Again, you will have to do
  3260.  
  3261.  
  3262.             #open "foo";;
  3263.  
  3264.  
  3265.     explicitly, for x to complete automatically into foo__x.
  3266.  
  3267.  
  3268. Chapter 5.   The toplevel system (camllight)                                55
  3269.  
  3270.  
  3271. 5.4 Common errors
  3272.  
  3273. This section describes and explains the most frequently encountered error
  3274. messages.
  3275.  
  3276. Cannot find file filename
  3277.     The named file could not be found in the current directory, nor in the
  3278.     directories of the search path.
  3279.  
  3280.     If filename has the format mod.zi, this means the current phrase
  3281.     references identifiers from module mod, but you have not yet compiled an
  3282.     interface for module mod.  Fix:  either load the file mod.ml, which will
  3283.     also create in memory the compiled interface for module mod; or use camlc
  3284.     to compile mod.mli or mod.ml, creating the compiled interface mod.zi,
  3285.     before you start the toplevel.
  3286.  
  3287.     If filename has the format mod.zo, this means you are trying to load with
  3288.     load_object a bytecode object file that does not exist yet.  Fix:
  3289.     compile mod.ml with camlc before you start the toplevel.  Or, use load
  3290.     instead of load_object to load the source code instead of a compiled
  3291.     object file.
  3292.  
  3293.     If filename has the format mod.ml, this means load or include could not
  3294.     find the specified source file.  Fix:  check the spelling of the file
  3295.     name, or write it if it does not exist.
  3296.  
  3297. mod__name is referenced before being defined
  3298.     You have neglected to load in memory an implementation for a module, with
  3299.     load or load_object.  This is explained in full detail in section 5.3
  3300.     above.
  3301.  
  3302. Corrupted compiled interface file filename
  3303.     See section 4.4.
  3304.  
  3305. Expression of type t1 cannot be used with type t2
  3306.     See section 4.4.
  3307.  
  3308.  
  3309. The type inferred for the value name, that is, t, contains type variables that cannot be generalized
  3310.  
  3311.     See section 4.4.
  3312.  
  3313.  
  3314. 5.5 Building custom toplevel systems:  camlmktop
  3315.  
  3316. The camlmktop command builds Caml Light toplevels that contain user code
  3317. preloaded at start-up.
  3318.  
  3319. Mac:  This command is not available in the Macintosh version.
  3320.  
  3321.   The camlmktop command takes as argument a set of .zo files, and links them
  3322. with the object files that implement the Caml Light toplevel.  The typical use
  3323. is:
  3324.  
  3325.         camlmktop -o mytoplevel foo.zo bar.zo gee.zo
  3326.  
  3327. This creates the bytecode file mytoplevel, containing the Caml Light toplevel
  3328. system, plus the code from the three .zo files.  To run this toplevel, give it
  3329.  
  3330.  
  3331. Chapter 5.   The toplevel system (camllight)                                56
  3332.  
  3333.  
  3334. as argument to the camllight command:
  3335.  
  3336.         camllight mytoplevel
  3337.  
  3338. This starts a regular toplevel loop, except that the code from foo.zo, bar.zo
  3339. and gee.zo is already loaded in memory, just as if you had typed:
  3340.  
  3341.         load_object "foo";;
  3342.         load_object "bar";;
  3343.         load_object "gee";;
  3344.  
  3345. on entrance to the toplevel.  The modules foo, bar and gee are not opened,
  3346. though; you still have to do
  3347.  
  3348.         #open "foo";;
  3349.  
  3350. yourself, if this is what you wish.
  3351.  
  3352.  
  3353. 5.6 Options
  3354.  
  3355. The following command-line options are recognized by camlmktop.
  3356.  
  3357. -ccopt option
  3358.     Pass the given option to the C compiler and linker, when linking in
  3359.     ``custom runtime'' mode.  See the corresponding option for camlc, in
  3360.     chapter 4.
  3361.  
  3362. -custom
  3363.     Link in ``custom runtime'' mode.  See the corresponding option for camlc,
  3364.     in chapter 4.
  3365.  
  3366. -g  Add debugging information to the toplevel file produced, which can then
  3367.     be debugged with camldebug (chapter 9).
  3368.  
  3369. -I directory
  3370.     Add the given directory to the list of directories searched for compiled
  3371.     object code files (.zo).
  3372.  
  3373. -o exec-file
  3374.     Specify the name of the toplevel file produced by the linker.
  3375.  
  3376.  
  3377.     Unix: The default is camltop.out.
  3378.  
  3379.  
  3380.     PC:   The default is camltop.exe.  The name must have .exe extension.
  3381.  
  3382.  
  3383.  
  3384.  
  3385.  
  3386.  
  3387.  
  3388.  
  3389.  
  3390.  
  3391.  
  3392. Chapter 6
  3393.  
  3394.  
  3395.  
  3396. The runtime system (camlrun)
  3397.  
  3398.  
  3399.  
  3400. The camlrun command executes bytecode files produced by the linking phase of
  3401. the camlc command.
  3402.  
  3403. Mac:  This command is a MPW tool, not a standalone Macintosh application.
  3404.  
  3405.  
  3406. 6.1 Overview
  3407.  
  3408. The camlrun command comprises three main parts:  the bytecode interpreter,
  3409. that actually executes bytecode files; the memory allocator and garbage
  3410. collector; and a set of C functions that implement primitive operations such
  3411. as input/output.
  3412.   The usage for camlrun is:
  3413.  
  3414.         camlrun options bytecode-executable arg1 ... argn
  3415.  
  3416. The first non-option argument is taken to be the name of the file containing
  3417. the executable bytecode.  (That file is searched in the executable path as
  3418. well as in the current directory.)  The remaining arguments are passed to the
  3419. Caml Light program, in the string array sys__command_line.  Element 0 of this
  3420. array is the name of the bytecode executable file; elements 1 to n are the
  3421. remaining arguments arg1 to argn.
  3422.   As mentioned in chapter 4, in most cases, the bytecode executable files
  3423. produced by the camlc command are self-executable, and manage to launch the
  3424. camlrun command on themselves automatically.  That is, assuming caml.out is a
  3425. bytecode executable file,
  3426.  
  3427.         caml.out arg1 ... argn
  3428.  
  3429. works exactly as
  3430.  
  3431.         camlrun caml.out arg1 ... argn
  3432.  
  3433. Notice that it is not possible to pass options to camlrun when invoking
  3434. caml.out directly.
  3435.  
  3436.  
  3437. 6.2 Options
  3438.  
  3439. The following command-line option is recognized by camlrun.
  3440.  
  3441. -V  Print out the camlrun version number.  Exit immediately without executing
  3442.     any byte-code file.
  3443.  
  3444.  
  3445.  
  3446.                                       57
  3447.  
  3448.  
  3449. Chapter 6.   The runtime system (camlrun)                                   58
  3450.  
  3451.  
  3452. The following environment variable are also consulted:
  3453.  
  3454. CAMLRUNPARAM
  3455.     Set the garbage collection parameters.  This variable must be a sequence
  3456.     of parameter specifications.  A parameter specification is an option
  3457.     letter followed by an = sign and a decimal number.  There are four
  3458.     options, corresponding to the four fields of the control record
  3459.     documented in section 14.5:
  3460.  
  3461.  
  3462.     s   (minor_heap_size) Size of the minor heap.
  3463.  
  3464.     i   (major_heap_increment) Minimum size increment for the major heap.
  3465.  
  3466.     o   (space_overhead) The major GC speed setting.
  3467.  
  3468.     v   (verbose) Whether to print GC messages or not.  0 is false; 1 is
  3469.         true; other values may give unexpected results.
  3470.  
  3471.  
  3472.     For example, under csh the command
  3473.  
  3474.  
  3475.             setenv CAMLRUNPARAM 's=250000 v=1'
  3476.  
  3477.  
  3478.     tells a subsequent camlrun to set its initial minor heap size to about
  3479.     1 megabyte (on a 32-bit machine) and to print its GC messages.
  3480.  
  3481. PATH
  3482.     List of directories searched to find the bytecode executable file.
  3483.  
  3484.  
  3485. 6.3 Common errors
  3486.  
  3487. This section describes and explains the most frequently encountered error
  3488. messages.
  3489.  
  3490. filename: no such file or directory
  3491.     If filename is the name of a self-executable bytecode file, this means
  3492.     that either that file does not exist, or that it failed to run the
  3493.     camlrun bytecode interpreter on itself.  The second possibility indicates
  3494.     that Caml Light has not been properly installed on your system.
  3495.  
  3496. Cannot exec camlrun
  3497.     (When launching a self-executable bytecode file.)  The camlrun command
  3498.     could not be found in the executable path.  Check that Caml Light has
  3499.     been properly installed on your system.
  3500.  
  3501. Cannot find the bytecode file
  3502.     The file that camlrun is trying to execute (e.g.  the file given as first
  3503.     non-option argument to camlrun) either does not exist, or is not a valid
  3504.     executable bytecode file.
  3505.  
  3506. Truncated bytecode file
  3507.     The file that camlrun is trying to execute is not a valid executable
  3508.     bytecode file.  Probably it has been truncated or mangled since created.
  3509.     Erase and rebuild it.
  3510.  
  3511.  
  3512. Chapter 6.   The runtime system (camlrun)                                   59
  3513.  
  3514.  
  3515. Uncaught exception
  3516.     The program being executed contains a ``stray'' exception.  That is, it
  3517.     raises an exception at some point, and this exception is never caught.
  3518.     This causes immediate termination of the program.  If you wish to know
  3519.     which exception thus escapes, use the printexc__f function from the
  3520.     standard library (and don't forget to link your program with the -g
  3521.     option).
  3522.  
  3523. Out of memory
  3524.     The program being executed requires more memory than available.  Either
  3525.     the program builds too large data structures; or the program contains too
  3526.     many nested function calls, and the stack overflows.  In some cases, your
  3527.     program is perfectly correct, it just requires more memory than your
  3528.     machine provides.  (This happens quite frequently on small
  3529.     microcomputers, but is unlikely on Unix machines.)  In other cases, the
  3530.     ``out of memory'' message reveals an error in your program:
  3531.     non-terminating recursive function, allocation of an excessively large
  3532.     array or string, attempts to build an infinite list or other data
  3533.     structure, ...
  3534.  
  3535.     To help you diagnose this error, run your program with the -v option to
  3536.     camlrun.  If it displays lots of ``Growing stack...''  messages, this is
  3537.     probably a looping recursive function.  If it displays lots of ``Growing
  3538.     heap...''  messages, with the heap size growing slowly, this is probably
  3539.     an attempt to construct a data structure with too many (infinitely many?)
  3540.     cells.  If it displays few ``Growing heap...''  messages, but with a huge
  3541.     increment in the heap size, this is probably an attempt to build an
  3542.     excessively large array or string.
  3543.  
  3544.  
  3545.  
  3546.  
  3547.  
  3548.  
  3549.  
  3550.  
  3551.  
  3552.  
  3553.  
  3554. Chapter 7
  3555.  
  3556.  
  3557.  
  3558. The librarian (camllibr)
  3559.  
  3560.  
  3561.  
  3562. Mac:  This command is a MPW tool, not a standalone Macintosh application.
  3563.  
  3564.  
  3565. 7.1 Overview
  3566.  
  3567. The camllibr program packs in one single file a set of bytecode object files
  3568. (.zo files).  The resulting file is also a bytecode object file and also has
  3569. the .zo extension.  It can be passed to the link phase of the camlc compiler
  3570. in replacement of the original set of bytecode object files.  That is, after
  3571. running
  3572.  
  3573.         camllibr -o library.zo mod1.zo mod2.zo mod3.zi mod4.zo
  3574.  
  3575. all calls to the linker with the form
  3576.  
  3577.         camlc ... library.zo ...
  3578.  
  3579. are exactly equivalent to
  3580.  
  3581.         camlc ... mod1.zo mod2.zo mod3.zi mod4.zo ...
  3582.  
  3583.   The typical use of camllibr is to build a library composed of several
  3584. modules:  this way, users of the library have only one .zo file to specify on
  3585. the command line to camlc, instead of a bunch of .zo files, one per module
  3586. contained in the library.
  3587.   The linking phase of camlc is clever enough to discard the code
  3588. corresponding to useless phrases:  in particular, definitions for global
  3589. variables that are never used after their definitions.  Hence, there is no
  3590. problem with putting many modules, even rarely used ones, into one single
  3591. library:  this will not result in bigger executables.
  3592.   The usage for camllibr is:
  3593.  
  3594.         camllibr options file1.zo ... filen.zo
  3595.  
  3596. where file1.zo through filen.zo are the object files to pack together.  The
  3597. order in which these file names are presented on the command line is relevant:
  3598. the compiled phrases contained in the library will be executed in that order.
  3599. (Remember that it is a link-time error to refer to a global variable that has
  3600. not yet been defined.)
  3601.  
  3602.  
  3603. 7.2 Options
  3604.  
  3605. The following command-line options are recognized by camllibr.
  3606.  
  3607.  
  3608.                                       60
  3609.  
  3610.  
  3611. Chapter 7.   The librarian (camllibr)                                       61
  3612.  
  3613.  
  3614. -files response-file
  3615.     Process the files whose names are listed in file response-file, just as
  3616.     if these names appeared on the command line.  File names in response-file
  3617.     are separated by blanks (spaces, tabs, newlines).  This option allows to
  3618.     overcome silly limitations on the length of the command line.
  3619.  
  3620. -I directory
  3621.     Add the given directory to the list of directories searched for the input
  3622.     .zo files.  By default, the current directory is searched first, then the
  3623.     standard library directory.  Directories added with -I are searched after
  3624.     the current directory, but before the standard library directory.  When
  3625.     several directories are added with several -I options on the command
  3626.     line, these directories are searched from right to left (the rightmost
  3627.     directory is searched first, the leftmost is searched last).
  3628.  
  3629. -o library-name
  3630.     Specify the name of the output file.  The default is library.zo.
  3631.  
  3632.  
  3633. 7.3 Turning code into a library
  3634.  
  3635. To develop a library, it is usually more convenient to split it into several
  3636. modules, that reflect the internal structure of the library.  From the
  3637. standpoint of the library users, however, it is preferable to view the library
  3638. as a single module, with only one interface file (.zi file) and one
  3639. implementation file (.zo file):  linking is easier, and there is no need to
  3640. put a bunch of #open directives, nor to have to remember the internal
  3641. structure of the library.
  3642.   The camllibr command allows having a single .zo file for the whole library.
  3643. Here is how the Caml Light module system can be used (some say ``abused'') to
  3644. have a single .zi file for the whole library.  To be more concrete, assume
  3645. that the library comprises three modules, windows, images and buttons.  The
  3646. idea is to add a fourth module, mylib, that re-exports the public parts of
  3647. windows, images and buttons.  The interface mylib.mli contains definitions for
  3648. those types that are public (exported with their definitions), declarations
  3649. for those types that are abstract (exported without their definitions), and
  3650. declarations for the functions that can be called from the user's code:
  3651.  
  3652. (* File mylib.mli *)
  3653. type 'a option = None | Some of 'a;;    (* a public type *)
  3654. type window and image and button;;      (* three abstract types *)
  3655. value new_window : int -> int -> window (* the public functions *)
  3656.   and draw_image : image -> window -> int -> int -> unit
  3657.   and ...
  3658.  
  3659. The implementation of the mylib module simply equates the abstract types and
  3660. the public functions to the corresponding types and functions in the modules
  3661. windows, images and buttons:
  3662.  
  3663. (* File mylib.ml *)
  3664. type window == windows__win
  3665.  and image  == images__pixmap
  3666.  and button == buttons__t;;
  3667. let new_window = windows__open_window
  3668. and draw_image = images__draw
  3669. and ...
  3670.  
  3671. The files windows.ml, images.ml and buttons.ml can open the mylib module, to
  3672.  
  3673.  
  3674. Chapter 7.   The librarian (camllibr)                                       62
  3675.  
  3676.  
  3677. access the public types defined in the interface mylib.mli, such as the option
  3678. type.  Of course, these modules must not reference the abstract types nor the
  3679. public functions, to avoid circularities.
  3680.   Types such as windows__win in the example above can be exported by the
  3681. windows module either abstractly or concretely (with their definition).
  3682. Often, it is necessary to export them concretely, because the other modules in
  3683. the library (images, buttons) need to build or destructure directly values of
  3684. that type.  Even if windows__win is exported concretely by the windows module,
  3685. that type will remain abstract to the library user, since it is abstracted by
  3686. the public interface mylib.
  3687.   The actual building of the library mylib proceeds as follows:
  3688.  
  3689. camlc -c mylib.mli              # create mylib.zi
  3690. camlc -c windows.mli windows.ml images.mli images.ml
  3691. camlc -c buttons.mli buttons.ml
  3692. camlc -c mylib.ml               # create mylib.zo
  3693. mv mylib.zo tmplib.zo           # renaming to avoid overwriting mylib.zo
  3694. camllibr -o mylib.zo windows.zo images.zo buttons.zo tmplib.zo
  3695.  
  3696. Then, copy mylib.zi and mylib.zo to a place accessible to the library users.
  3697. The other .zi and .zo files need not be copied.
  3698.  
  3699.  
  3700.  
  3701.  
  3702.  
  3703.  
  3704.  
  3705.  
  3706.  
  3707.  
  3708.  
  3709. Chapter 8
  3710.  
  3711.  
  3712.  
  3713. Lexer and parser generators (camllex, camlyacc)
  3714.  
  3715.  
  3716.  
  3717. This chapter describes two program generators:  camllex, that produces a
  3718. lexical analyzer from a set of regular expressions with associated semantic
  3719. actions, and camlyacc, that produces a parser from a grammar with associated
  3720. semantic actions.
  3721.   These program generators are very close to the well-known lex and yacc
  3722. commands that can be found in most C programming environments.  This chapter
  3723. assumes a working knowledge of lex and yacc:  while it describes the input
  3724. syntax for camllex and camlyacc and the main differences with lex and yacc, it
  3725. does not explain the basics of writing a lexer or parser description in lex
  3726. and yacc.  Readers unfamiliar with lex and yacc are referred to ``Compilers:
  3727. principles, techniques, and tools'' by Aho, Sethi and Ullman (Addison-Wesley,
  3728. 1986), ``Compiler design in C'' by Holub (Prentice-Hall, 1990), or ``Lex &
  3729. Yacc'', by Mason and Brown (O'Reilly, 1990).
  3730.   Streams and stream matching, as described in section 3.1, provide an
  3731. alternative way to write lexers and parsers.  The stream matching technique is
  3732. more powerful than the combination of camllex and camlyacc in some cases
  3733. (higher-order parsers), but less powerful in other cases (precedences).
  3734. Choose whichever approach is more adapted to your parsing problem.
  3735.  
  3736. Mac:  These commands are MPW tool, not standalone Macintosh applications.
  3737.  
  3738.  
  3739. 8.1 Overview of camllex
  3740.  
  3741. The camllex command produces a lexical analyzer from a set of regular
  3742. expressions with attached semantic actions, in the style of lex.  Assuming the
  3743. input file is lexer.mll, executing
  3744.  
  3745.         camllex lexer.mll
  3746.  
  3747. produces Caml Light code for a lexical analyzer in file lexer.ml.  This file
  3748. defines one lexing function per entry point in the lexer definition.  These
  3749. functions have the same names as the entry points.  Lexing functions take as
  3750. argument a lexer buffer, and return the semantic attribute of the
  3751. corresponding entry point.
  3752.   Lexer buffers are an abstract data type implemented in the standard library
  3753. module lexing.  The functions create_lexer_channel, create_lexer_string and
  3754. create_lexer from module lexing create lexer buffers that read from an input
  3755. channel, a character string, or any reading function, respectively.  (See the
  3756. description of module lexing in chapter 13.)
  3757.   When used in conjunction with a parser generated by camlyacc, the semantic
  3758. actions compute a value belonging to the type token defined by the generated
  3759. parsing module.  (See the description of camlyacc below.)
  3760.  
  3761.  
  3762.                                       63
  3763.  
  3764.  
  3765. Chapter 8.   Lexer and parser generators (camllex, camlyacc)                64
  3766.  
  3767.  
  3768. 8.2 Syntax of lexer definitions
  3769.  
  3770. The format of lexer definitions is as follows:
  3771.  
  3772. { header }
  3773. rule entrypoint =
  3774.   parse regexp { action }
  3775.       | ...
  3776.       | regexp { action }
  3777. and entrypoint =
  3778.   parse ...
  3779. and ...
  3780. ;;
  3781.  
  3782.   Comments are delimited by (* and *), as in Caml Light.
  3783.  
  3784. 8.2.1 Header
  3785.  
  3786. The header section is arbitrary Caml Light text enclosed in curly braces.  It
  3787. can be omitted.  If it is present, the enclosed text is copied as is at the
  3788. beginning of the output file.  Typically, the header section contains the
  3789. #open directives required by the actions, and possibly some auxiliary
  3790. functions used in the actions.
  3791.  
  3792. 8.2.2 Entry points
  3793.  
  3794. The names of the entry points must be valid Caml Light identifiers.
  3795.  
  3796. 8.2.3 Regular expressions
  3797.  
  3798. The regular expressions are in the style of lex, with a more Caml-like syntax.
  3799.  
  3800. ` char `
  3801.     A character constant, with the same syntax as Caml Light character
  3802.     constants.  Match the denoted character.
  3803.  
  3804. _   Match any character.
  3805.  
  3806. eof Match the end of the lexer input.
  3807.  
  3808. " string "
  3809.     A string constant, with the same syntax as Caml Light string constants.
  3810.     Match the corresponding sequence of characters.
  3811.  
  3812. [ character-set ]
  3813.     Match any single character belonging to the given character set.  Valid
  3814.     character sets are:  single character constants ` c `; ranges of
  3815.     characters ` c1 ` - ` c2 ` (all characters between c1 and c2, inclusive);
  3816.     and the union of two or more character sets, denoted by concatenation.
  3817.  
  3818. [ ^ character-set ]
  3819.     Match any single character not belonging to the given character set.
  3820.  
  3821. regexp *
  3822.     (Repetition.)  Match the concatenation of zero or more strings that match
  3823.     regexp.
  3824.  
  3825.  
  3826. Chapter 8.   Lexer and parser generators (camllex, camlyacc)                65
  3827.  
  3828.  
  3829. regexp +
  3830.     (Strict repetition.)  Match the concatenation of one or more strings that
  3831.     match regexp.
  3832.  
  3833. regexp ?
  3834.     (Option.)  Match either the empty string, or a string matching regexp.
  3835.  
  3836. regexp1 | regexp2
  3837.     (Alternative.)  Match any string that matches either regexp1 or regexp2
  3838.  
  3839. regexp1 regexp2
  3840.     (Concatenation.)  Match the concatenation of two strings, the first
  3841.     matching regexp1, the second matching regexp2.
  3842.  
  3843. ( regexp )
  3844.     Match the same strings as regexp.
  3845.  
  3846.   Concerning the precedences of operators, * and + have highest precedence,
  3847. followed by ?, then concatenation, then | (alternation).
  3848.  
  3849. 8.2.4 Actions
  3850.  
  3851. The actions are arbitrary Caml Light expressions.  They are evaluated in a
  3852. context where the identifier lexbuf is bound to the current lexer buffer.
  3853. Some typical uses for lexbuf, in conjunction with the operations on lexer
  3854. buffers provided by the lexing standard library module, are listed below.
  3855.  
  3856. lexing__get_lexeme lexbuf
  3857.     Return the matched string.
  3858.  
  3859. lexing__get_lexeme_char lexbuf n
  3860.                 th
  3861.     Return the n  character in the matched string.  The first character
  3862.     corresponds to n=0.
  3863.  
  3864. lexing__get_lexeme_start lexbuf
  3865.     Return the absolute position in the input text of the beginning of the
  3866.     matched string.  The first character read from the input text has
  3867.     position 0.
  3868.  
  3869. lexing__get_lexeme_end lexbuf
  3870.     Return the absolute position in the input text of the end of the matched
  3871.     string.  The first character read from the input text has position 0.
  3872.  
  3873. entrypoint lexbuf
  3874.     (Where entrypoint is the name of another entry point in the same lexer
  3875.     definition.)  Recursively call the lexer on the given entry point.
  3876.     Useful for lexing nested comments, for example.
  3877.  
  3878.  
  3879. 8.3 Overview of camlyacc
  3880.  
  3881. The camlyacc command produces a parser from a context-free grammar
  3882. specification with attached semantic actions, in the style of yacc.  Assuming
  3883. the input file is grammar.mly, executing
  3884.  
  3885.         camlyacc options grammar.mly
  3886.  
  3887.  
  3888. Chapter 8.   Lexer and parser generators (camllex, camlyacc)                66
  3889.  
  3890.  
  3891. produces Caml Light code for a parser in the file grammar.ml, and its
  3892. interface in file grammar.mli.
  3893.   The generated module defines one parsing function per entry point in the
  3894. grammar.  These functions have the same names as the entry points.  Parsing
  3895. functions take as arguments a lexical analyzer (a function from lexer buffers
  3896. to tokens) and a lexer buffer, and return the semantic attribute of the
  3897. corresponding entry point.  Lexical analyzer functions are usually generated
  3898. from a lexer specification by the camllex program.  Lexer buffers are an
  3899. abstract data type implemented in the standard library module lexing.  Tokens
  3900. are values from the concrete type token, defined in the interface file
  3901. grammar.mli produced by camlyacc.
  3902.  
  3903.  
  3904. 8.4 Syntax of grammar definitions
  3905.  
  3906. Grammar definitions have the following format:
  3907.  
  3908. %{
  3909.   header
  3910. %}
  3911.   declarations
  3912. %%
  3913.   rules
  3914. %%
  3915.   trailer
  3916.  
  3917.   Comments are enclosed between /* and */ (as in C) in the ``declarations''
  3918. and ``rules'' sections, and between (* and *) (as in Caml) in the ``header''
  3919. and ``trailer'' sections.
  3920.  
  3921. 8.4.1 Header and trailer
  3922.  
  3923. The header and the trailer sections are Caml Light code that is copied as is
  3924. into file grammar.ml.  Both sections are optional.  The header goes at the
  3925. beginning of the output file; it usually contains #open directives required by
  3926. the semantic actions of the rules.  The trailer goes at the end of the output
  3927. file.
  3928.  
  3929. 8.4.2 Declarations
  3930.  
  3931. Declarations are given one per line.  They all start with a % sign.
  3932.  
  3933. %token symbol...symbol
  3934.     Declare the given symbols as tokens (terminal symbols).  These symbols
  3935.     are added as constant constructors for the token concrete type.
  3936.  
  3937. %token < type > symbol...symbol
  3938.     Declare the given symbols as tokens with an attached attribute of the
  3939.     given type.  These symbols are added as constructors with arguments of
  3940.     the given type for the token concrete type.  The type part is an
  3941.     arbitrary Caml Light type expression, except that all type constructor
  3942.     names must be fully qualified (e.g.  modname__typename) for all types
  3943.     except standard built-in types, even if the proper #open directives (e.g.
  3944.     #open "modname") were given in the header section.  That's because the
  3945.     header is copied only to the .ml output file, but not to the .mli output
  3946.     file, while the type part of a %token declaration is copied to both.
  3947.  
  3948.  
  3949. Chapter 8.   Lexer and parser generators (camllex, camlyacc)                67
  3950.  
  3951.  
  3952. %start symbol...symbol
  3953.     Declare the given symbols as entry points for the grammar.  For each
  3954.     entry point, a parsing function with the same name is defined in the
  3955.     output module.  Non-terminals that are not declared as entry points have
  3956.     no such parsing function.  Start symbols must be given a type with the
  3957.     %type directive below.
  3958.  
  3959. %type < type > symbol...symbol
  3960.     Specify the type of the semantic attributes for the given symbols.  This
  3961.     is mandatory for start symbols only.  Other nonterminal symbols need not
  3962.     be given types by hand:  these types will be inferred when running the
  3963.     output files through the Caml Light compiler (unless the -s option is in
  3964.     effect).  The type part is an arbitrary Caml Light type expression,
  3965.     except that all type constructor names must be fully qualified (e.g.
  3966.     modname__typename) for all types except standard built-in types, even if
  3967.     the proper #open directives (e.g.  #open "modname") were given in the
  3968.     header section.  That's because the header is copied only to the .ml
  3969.     output file, but not to the .mli output file, while the type part of a
  3970.     %token declaration is copied to both.
  3971.  
  3972. %left symbol...symbol
  3973.  
  3974.  
  3975. %right symbol...symbol
  3976.  
  3977.  
  3978. %nonassoc symbol...symbol
  3979.  
  3980.  
  3981.     Associate precedences and associativities to the given symbols.  All
  3982.     symbols on the same line are given the same precedence.  They have higher
  3983.     precedence than symbols declared before in a %left, %right or %nonassoc
  3984.     line.  They have lower precedence than symbols declared after in a %left,
  3985.     %right or %nonassoc line.  The symbols are declared to associate to the
  3986.     left (%left), to the right (%right), or to be non-associative
  3987.     (%nonassoc).  The symbols are usually tokens.  They can also be dummy
  3988.     nonterminals, for use with the %prec directive inside the rules.
  3989.  
  3990. 8.4.3 Rules
  3991.  
  3992. The syntax for rules is as usual:
  3993.  
  3994. nonterminal :
  3995.     symbol ... symbol { semantic-action }
  3996.   | ...
  3997.   | symbol ... symbol { semantic-action }
  3998. ;
  3999.  
  4000. Rules can also contain the %prec symbol directive in the right-hand side part,
  4001. to override the default precedence and associativity of the rule with the
  4002. precedence and associativity of the given symbol.
  4003.   Semantic actions are arbitrary Caml Light expressions, that are evaluated to
  4004. produce the semantic attribute attached to the defined nonterminal.  The
  4005. semantic actions can access the semantic attributes of the symbols in the
  4006. right-hand side of the rule with the $ notation:  $1 is the attribute for the
  4007. first (leftmost) symbol, $2 is the attribute for the second symbol, etc.
  4008.   Actions occurring in the middle of rules are not supported.  Error recovery
  4009. is not implemented.
  4010.  
  4011.  
  4012. Chapter 8.  Lexer and parser generators (camllex, camlyacc)                 68
  4013.  
  4014.  
  4015. 8.5 Options
  4016.  
  4017. The camlyacc command recognizes the following options:
  4018.  
  4019. -v  Generate a description of the parsing tables and a report on conflicts
  4020.     resulting from ambiguities in the grammar.  The description is put in
  4021.     file grammar.output.
  4022.  
  4023. -s  Generate a grammar.ml file with smaller phrases.  Semantic actions are
  4024.     presented in the grammar.ml output file as one large vector of functions.
  4025.     By default, this vector is built by a single phrase.  When the grammar is
  4026.     large, or contains complicated semantic actions, the resulting phrase may
  4027.     require large amounts of memory to be compiled by Caml Light.  With the
  4028.     -s option, the vector of actions is constructed incrementally, one phrase
  4029.     per action.  This lowers the memory requirements for the compiler, but it
  4030.     is no longer possible to infer the types of nonterminal symbols:
  4031.     typechecking is turned off on symbols that do not have a type specified
  4032.     by a %type directive.
  4033.  
  4034. -bprefix
  4035.     Name the output files prefix.ml, prefix.mli, prefix.output, instead of
  4036.     the default naming convention.
  4037.  
  4038.  
  4039. 8.6 A complete example
  4040.  
  4041. The all-time favorite:  a desk calculator.  This program reads arithmetic
  4042. expressions on standard input, one per line, and prints their values.  Here is
  4043. the grammar definition:
  4044.  
  4045.         /* File parser.mly */
  4046.         %token <int> INT
  4047.         %token PLUS MINUS TIMES DIV
  4048.         %token LPAREN RPAREN
  4049.         %token EOL
  4050.         %left PLUS MINUS        /* lowest precedence */
  4051.         %left TIMES DIV         /* medium precedence */
  4052.         %nonassoc UMINUS        /* highest precedence */
  4053.         %start Main             /* the entry point */
  4054.         %type <int> Main
  4055.         %%
  4056.         Main:
  4057.             Expr EOL                { $1 }
  4058.         ;
  4059.         Expr:
  4060.             INT                     { $1 }
  4061.           | LPAREN Expr RPAREN      { $2 }
  4062.           | Expr PLUS Expr          { $1 + $3 }
  4063.           | Expr MINUS Expr         { $1 - $3 }
  4064.           | Expr TIMES Expr         { $1 * $3 }
  4065.           | Expr DIV Expr           { $1 / $3 }
  4066.           | MINUS Expr %prec UMINUS { - $2 }
  4067.         ;
  4068.  
  4069. Here is the definition for the corresponding lexer:
  4070.  
  4071.         (* File lexer.mll *)
  4072.         {
  4073.  
  4074.  
  4075. Chapter 8.   Lexer and parser generators (camllex, camlyacc)                69
  4076.  
  4077.  
  4078.         #open "parser";;        (* The type token is defined in parser.mli *)
  4079.         exception Eof;;
  4080.         }
  4081.         rule Token = parse
  4082.             [` ` `\t`]     { Token lexbuf }     (* skip blanks *)
  4083.           | [`\n` ]        { EOL }
  4084.           | [`0`-`9`]+     { INT(int_of_string (get_lexeme lexbuf)) }
  4085.           | `+`            { PLUS }
  4086.           | `-`            { MINUS }
  4087.           | `*`            { TIMES }
  4088.           | `/`            { DIV }
  4089.           | `(`            { LPAREN }
  4090.           | `)`            { RPAREN }
  4091.           | eof            { raise Eof }
  4092.         ;;
  4093.  
  4094. Here is the main program, that combines the parser with the lexer:
  4095.  
  4096.         (* File calc.ml *)
  4097.         try
  4098.           let lexbuf = lexing__create_lexer_channel std_in in
  4099.           while true do
  4100.             let result = parser__Main lexer__Token lexbuf in
  4101.               print_int result; print_newline(); flush std_out
  4102.           done
  4103.         with Eof ->
  4104.           ()
  4105.         ;;
  4106.  
  4107. To compile everything, execute:
  4108.  
  4109.         camllex lexer.mll       # generates lexer.ml
  4110.         camlyacc parser.mly     # generates parser.ml and parser.mli
  4111.         camlc -c parser.mli
  4112.         camlc -c lexer.ml
  4113.         camlc -c parser.ml
  4114.         camlc -c calc.ml
  4115.         camlc -o calc lexer.zo parser.zo calc.zo
  4116.  
  4117.  
  4118.  
  4119.  
  4120.  
  4121.  
  4122.  
  4123.  
  4124.  
  4125.  
  4126.  
  4127. Chapter 9
  4128.  
  4129.  
  4130.  
  4131. The debugger (camldebug)
  4132.  
  4133.  
  4134.  
  4135. This chapter describes the Caml Light source-level replay debugger camldebug.
  4136.  
  4137. Unix: The debugger resides in the directory contrib/debugger in the
  4138.       distribution.  It requires a Unix system that provides BSD sockets.
  4139.  
  4140. Mac:  The debugger is not available.
  4141.  
  4142. PC:   The debugger is not available.
  4143.  
  4144.  
  4145. 9.1 Compiling for debugging
  4146.  
  4147. Before the debugger can be used, the program must be compiled and linked with
  4148. the -g option:  all .zo files that are part of the program should have been
  4149. created with camlc -g, and they must be linked together with camlc -g.
  4150.   Compiling with -g entails no penalty on the running time of programs:  .zo
  4151. files and bytecode executable files are bigger and take slightly longer to
  4152. produce, but the executable files run at exactly the same speed as if they had
  4153. been compiled without -g.  It is therefore perfectly acceptable to compile
  4154. always in -g mode.
  4155.  
  4156.  
  4157. 9.2 Invocation
  4158.  
  4159. 9.2.1 Starting the debugger
  4160.  
  4161. The Caml Light debugger is invoked by running the program camldebug with the
  4162. name of the bytecode executable file as argument:
  4163.  
  4164.         camldebug program
  4165.  
  4166. The following command-line options are recognized:
  4167.  
  4168. -stdlib directory
  4169.     Look for the standard library files in directory instead of in the
  4170.     default directory.
  4171.  
  4172. -s socket
  4173.     Use socket for communicating with the debugged program.  See the
  4174.     description of the command set socket (section 9.8.7) for the format of
  4175.     socket.
  4176.  
  4177. -c  count
  4178.     Set the maximum number of checkpoint to count.
  4179.  
  4180.  
  4181.                                       70
  4182.  
  4183.  
  4184. Chapter 9.   The debugger (camldebug)                                       71
  4185.  
  4186.  
  4187. -cd  directory
  4188.     Run the debugger program from the working directory directory, instead of
  4189.     the current directory.
  4190.  
  4191. -emacs
  4192.     Tell the debugger it is executed under Emacs.  (See section 11.4 for
  4193.     information on how to run the debugger under Emacs.)
  4194.  
  4195. 9.2.2 Quitting the debugger
  4196.  
  4197. The command quit exits the debugger.  You can also exit the debugger by typing
  4198. an end-of-file character (usually ctrl-D).
  4199.   Typing an interrupt character (usually ctrl-C) will not exit the debugger,
  4200. but will terminate the action of any debugger command that is in progress and
  4201. return to the debugger command level.
  4202.  
  4203.  
  4204. 9.3 Commands
  4205.  
  4206. A debugger command is a single line of input.  It starts with a command name,
  4207. which is followed by arguments depending on this name.  Examples:
  4208.  
  4209.         run
  4210.         goto 1000
  4211.         set arguments arg1 arg2
  4212.  
  4213.   A command name can be truncated as long as there is no ambiguity.  For
  4214. instance, go 1000 is understood as goto 1000, since there are no other
  4215. commands whose name starts with go.  For the most frequently used commands,
  4216. ambiguous abbreviations are allowed.  For instance, r stands for run even
  4217. though there are others commands starting with r.  You can test the validity
  4218. of an abbreviation using the help command.
  4219.   If the previous command has been successful, a blank line (typing just RET)
  4220. will repeat it.
  4221.  
  4222. 9.3.1 Getting help
  4223.  
  4224. The Caml Light debugger has a simple on-line help system, which gives a brief
  4225. description of each command and variable.
  4226.  
  4227. help
  4228.     Print the list of commands.
  4229.  
  4230. help command
  4231.     Give help about the command command.
  4232.  
  4233. help set variable, help show variable
  4234.     Give help about the variable variable.  The list of all debugger
  4235.     variables can be obtained with help set.
  4236.  
  4237. help info topic
  4238.     Give help about topic.  Use help info to get a list of known topics.
  4239.  
  4240. 9.3.2 Accessing the debugger state
  4241.  
  4242. set variable value
  4243.     Set the debugger variable variable to the value value.
  4244.  
  4245.  
  4246. Chapter 9.  The debugger (camldebug)                                        72
  4247.  
  4248.  
  4249. show variable
  4250.     Print the value of the debugger variable variable.
  4251.  
  4252. info subject
  4253.     Give information about the given subject.  For instance, info breakpoints
  4254.     will print the list of all breakpoints.
  4255.  
  4256.  
  4257. 9.4 Executing a program
  4258.  
  4259. 9.4.1 Events
  4260.  
  4261. Events are ``interesting'' locations in the source code, corresponding to the
  4262. beginning or end of evaluation of ``interesting'' sub-expressions.  Events are
  4263. the unit of single-stepping (stepping goes to the next or previous event
  4264. encountered in the program execution).  Also, breakpoints can only be set at
  4265. events.  Thus, events play the role of line numbers in debuggers for
  4266. conventional languages.
  4267.   During program execution, a counter is incremented at each event
  4268. encountered.  The value of this counter is referred as the current time.
  4269. Thanks to reverse execution, it is possible to jump back and forth to any time
  4270. of the execution.
  4271.   Here is where the debugger events (written <) are located in the source
  4272. code:
  4273.  
  4274.  -  Following a function application:
  4275.  
  4276.  
  4277.     (f arg)<
  4278.  
  4279.  
  4280.  -  After receiving an argument to a function:
  4281.  
  4282.  
  4283.     fun x< y>< z -> >< ...
  4284.  
  4285.  
  4286.     If a curried function is defined by pattern-matching with several cases,
  4287.     events corresponding to the passing of arguments are displayed on the
  4288.     first case of the function, because pattern-matching has not yet
  4289.     determined which case to select:
  4290.  
  4291.  
  4292.     fun pat1< pat2>< pat3 -> >< ...
  4293.       | ...
  4294.  
  4295.  
  4296.  -  On each case of a pattern-matching definition (function, match...with
  4297.     construct, try...with construct):
  4298.  
  4299.  
  4300.     function pat1 -> < expr1
  4301.            | ...
  4302.            | patN -> < exprN
  4303.  
  4304.  
  4305.  -  Between subexpressions of a sequence:
  4306.  
  4307.  
  4308. Chapter 9.   The debugger (camldebug)                                       73
  4309.  
  4310.  
  4311.     expr1; < expr2; >< ...; >< exprN
  4312.  
  4313.  
  4314.  -  In the two branches of a conditional expression:
  4315.  
  4316.  
  4317.     if cond then < expr1 else >< expr2
  4318.  
  4319.  
  4320.  -  At the beginning of each iteration of a loop:
  4321.  
  4322.  
  4323.     while cond do < body done
  4324.     for i = a to b do < body done
  4325.  
  4326.  
  4327. Exceptions:  A function application followed by a function return is replaced
  4328. by the compiler by a jump (tail-call optimization).  In this case, no event is
  4329. put after the function application.  Also, no event is put after a function
  4330. application when the function is a primitive function (written in C). Finally,
  4331. several events may correspond to the same location in the compiled program.
  4332. Then, the debugger cannot distinguish them, and selects one of the events to
  4333. associate with the given code location.  The event chosen is a ``function
  4334. application'' event if there is one at that location, or otherwise the event
  4335. which appears last in the source.  This heuristic generally picks the ``most
  4336. interesting'' event associated with the code location.
  4337.  
  4338. 9.4.2 Starting the debugged program
  4339.  
  4340. The debugger starts executing the debugged program only when needed.  This
  4341. allows setting breapoints or assigning debugger variables before execution
  4342. starts.  There are several ways to start execution:
  4343.  
  4344. run Run the program until a breakpoint is hit, or the program terminates.
  4345.  
  4346. step 0
  4347.     Load the program and stop on the first event.
  4348.  
  4349. goto time
  4350.     Load the program and execute it until the given time.  Useful when you
  4351.     already know approximately at what time the problem appears.  Also useful
  4352.     to set breakpoints on function values that have not been computed at time
  4353.     0 (see section 9.5).
  4354.  
  4355.   The execution of a program is affected by certain information it receives
  4356. when the debugger starts it, such as the command-line arguments to the program
  4357. and its working directory.  The debugger provides commands to specify this
  4358. information (set arguments and cd).  These commands must be used before
  4359. program execution starts.  If you try to change the arguments or the working
  4360. directory after starting your program, the debugger will kill the program
  4361. (after asking for confirmation).
  4362.  
  4363. 9.4.3 Running the program
  4364.  
  4365. The following commands execute the program forward or backward, starting at
  4366. the current time.  The execution will stop either when specified by the
  4367. command or when a breakpoint is encountered.
  4368.  
  4369.  
  4370. Chapter 9.   The debugger (camldebug)                                       74
  4371.  
  4372.  
  4373. run Execute the program forward from current time.  Stops at next breakpoint
  4374.     or when the program terminates.
  4375.  
  4376. reverse
  4377.     Execute the program backward from current time.  Mostly useful to go to
  4378.     the last breakpoint encountered before the current time.
  4379.  
  4380. step [count]
  4381.     Run the program and stop at the next event.  With an argument, do it
  4382.     count times.
  4383.  
  4384. backstep [count]
  4385.     Run the program backward and stop at the previous event.  With an
  4386.     argument, do it count times.
  4387.  
  4388. next [count]
  4389.     Run the program and stop at the next event, skipping over function calls.
  4390.     With an argument, do it count times.
  4391.  
  4392. finish
  4393.     Run the program until the current function returns.
  4394.  
  4395. 9.4.4 Time travel
  4396.  
  4397. You can jump directly to a given time, without stopping on breakpoints, using
  4398. the goto command.
  4399.   As you move through the program, the debugger maintains an history of the
  4400. successive times you stop at.  The last command can be used to revisit these
  4401. times:  each last command moves one step back through the history.  That is
  4402. useful mainly to undo commands such as step and next.
  4403.  
  4404. goto time
  4405.     Jump to the given time.
  4406.  
  4407. last [count]
  4408.     Go back to the latest time recorded in the execution history.  With an
  4409.     argument, do it count times.
  4410.  
  4411. set history size
  4412.     Set the size of the execution history.
  4413.  
  4414. 9.4.5 Killing the program
  4415.  
  4416. kill
  4417.     Kill the program being executed.  This command is mainly useful if you
  4418.     wish to recompile the program without leaving the debugger.
  4419.  
  4420.  
  4421. 9.5 Breakpoints
  4422.  
  4423. A breakpoint causes the program to stop whenever a certain point in the
  4424. program is reached.  It can be set in several ways using the break command.
  4425. Breakpoints are assigned numbers when set, for further reference.
  4426.  
  4427. break
  4428.     Set a breakpoint at the current position in the program execution.  The
  4429.     current position must be on an event (i.e., neither at the beginning, nor
  4430.     at the end of the program).
  4431.  
  4432.  
  4433. Chapter 9.   The debugger (camldebug)                                       75
  4434.  
  4435.  
  4436. break function
  4437.     Set a breakpoint at the beginning of function.  This works only when the
  4438.     functional value of the identifier function has been computed and
  4439.     assigned to the identifier.  Hence this command cannot be used at the
  4440.     very beginning of the program execution, when all identifiers are still
  4441.     undefined.  Moreover, C functions are not recognized by the debugger.
  4442.  
  4443. break @ [module] line
  4444.     Set a breakpoint in module module (or in the current module if module is
  4445.     not given), at the first event of line line.
  4446.  
  4447. break @ [module] line column
  4448.     Set a breakpoint in module module (or in the current module if module is
  4449.     not given), at the event closest to line line, column column.
  4450.  
  4451. break @ [module] # character
  4452.     Set a breakpoint in module module at the event closest to character
  4453.     number character.
  4454.  
  4455. break address
  4456.     Set a breakpoint at the code address address.
  4457.  
  4458. delete [breakpoint-numbers]
  4459.     Delete the specified breakpoints.  Without argument, all breakpoints are
  4460.     deleted (after asking for confirmation).
  4461.  
  4462. info breakpoints
  4463.     Print the list of all breakpoints.
  4464.  
  4465.  
  4466. 9.6 The call stack
  4467.  
  4468. Each time the program performs a function application, it saves the location
  4469. of the application (the return address) in a block of data called a stack
  4470. frame.  The frame also contains the local variables of the caller function.
  4471. All the frames are allocated in a region of memory called the call stack.  The
  4472. command backtrace (or bt) displays parts of the call stack.
  4473.   At any time, one of the stack frames is ``selected'' by the debugger;
  4474. several debugger commands refer implicitly to the selected frame.  In
  4475. particular, whenever you ask the debugger for the value of a local variable,
  4476. the value is found in the selected frame.  The commands frame, up and down
  4477. select whichever frame you are interested in.
  4478.   When the program stops, the debugger automatically selects the currently
  4479. executing frame and describes it briefly as the frame command does.
  4480.  
  4481. frame
  4482.     Describe the currently selected stack frame.
  4483.  
  4484. frame frame-number
  4485.     Select a stack frame by number and describe it.  The frame currently
  4486.     executing when the program stopped has number 0; its caller has number 1;
  4487.     and so on up the call stack.
  4488.  
  4489. backtrace [count], bt [count]
  4490.     Print the call stack.  This is useful to see which sequence of function
  4491.     calls led to the currently executing frame.  With a positive argument,
  4492.     print only the innermost count frames.  With a negative argument, print
  4493.     only the outermost -count frames.
  4494.  
  4495.  
  4496. Chapter 9.   The debugger (camldebug)                                       76
  4497.  
  4498.  
  4499. up [count]
  4500.     Select and display the stack frame just ``above'' the selected frame,
  4501.     that is, the frame that called the selected frame.  An argument says how
  4502.     many frames to go up.
  4503.  
  4504. down [count]
  4505.     Select and display the stack frame just ``below'' the selected frame,
  4506.     that is, the frame that was called by the selected frame.  An argument
  4507.     says how many frames to go down.
  4508.  
  4509.  
  4510. 9.7 Examining variable values
  4511.  
  4512. The debugger can print the current value of a program variable (either a
  4513. global variable or a local variable relative to the selected stack frame).  It
  4514. can also print selected parts of a value by matching it against a pattern.
  4515.   Variable names can be specified either fully qualified
  4516. (module-name__var-name) or unqualified (var-name).  Unqualified names either
  4517. correspond to local variables, or are completed into fully qualified global
  4518. names by looking at a list of ``opened'' modules that define the same name
  4519. (see section 9.8.5 for how to open modules in the debugger.)  The completion
  4520. follows the same rules as in the Caml Light language (see section 2.2).
  4521.  
  4522. print variables
  4523.     Print the values of the given variables.
  4524.  
  4525. match variable pattern
  4526.     Match the value of the given variable against a pattern, and print the
  4527.     values bound to the identifiers in the pattern.
  4528.  
  4529.   The syntax of patterns for the match command extends the one for Caml Light
  4530. patterns:
  4531.  
  4532.             pattern  ::=  ident
  4533.                        |  _
  4534.                        |  ( pattern )
  4535.                        |  ncconstr pattern
  4536.                        |  pattern , pattern {, pattern}
  4537.                        |  { label = pattern {; label = pattern} }
  4538.                        |  [ ]
  4539.                        |  [ pattern {; pattern} ]
  4540.                        |  pattern :: pattern
  4541.                        |  # integer-literal pattern
  4542.                        |  > pattern
  4543.  
  4544.   The pattern ident, where ident is an identifier, matches any value, and
  4545. binds the identifier to this value.  The pattern # n pattern matches a list, a
  4546. vector or a tuple whose n-th element matches pattern.  The pattern > pattern
  4547. matches any constructed value whose argument matches pattern, regardless of
  4548. the constructor; it is a shortcut for skipping a constructor.
  4549.   Example:  assuming the value of a is Constr{x = [1;2;3;4]}, the command
  4550. match a > {x = # 2 k} prints k = 3.
  4551.  
  4552. set print_depth d
  4553.     Limit the printing of values to a maximal depth of d.
  4554.  
  4555. set print_length l
  4556.     Limit the printing of values to at most l nodes printed.
  4557.  
  4558.  
  4559. Chapter 9.   The debugger (camldebug)                                       77
  4560.  
  4561.  
  4562. 9.8 Controlling the debugger
  4563.  
  4564. 9.8.1 Setting the program name and arguments
  4565.  
  4566. set program file
  4567.     Set the program name to file.
  4568.  
  4569. set arguments arguments
  4570.     Give arguments as command-line arguments for the program.
  4571.  
  4572.   A shell is used to pass the arguments to the debugged program.  You can
  4573. therefore use wildcards, shell variables, and file redirections inside the
  4574. arguments.  To debug programs that read from standard input, it is recommended
  4575. to redirect their input from a file (using set arguments < input-file),
  4576. otherwise input to the program and input to the debugger are not properly
  4577. separated.
  4578.  
  4579. 9.8.2 How programs are loaded
  4580.  
  4581. The loadingmode variable controls how the program is executed.
  4582.  
  4583. set loadingmode direct
  4584.     The program is run directly by the debugger.  This is the default mode.
  4585.  
  4586. set loadingmode runtime
  4587.     The debugger execute the Caml Light runtime camlrun on the program.
  4588.     Rarely useful; moreover it prevents the debugging of programs compiled in
  4589.     ``custom runtime'' mode.
  4590.  
  4591. set loadingmode manual
  4592.     The user starts manually the program, when asked by the debugger.  Allows
  4593.     remote debugging (see section 9.8.7).
  4594.  
  4595. 9.8.3 Search path for files
  4596.  
  4597. The debugger searches for source files and compiled interface files in a list
  4598. of directories, the search path.  The search path initially contains the
  4599. current directory .  and the standard library directory.  The directory
  4600. command adds directories to the path.
  4601.   Whenever the search path is modified, the debugger will clear any
  4602. information it may have cached about the files.
  4603.  
  4604. directory directorynames
  4605.     Add the given directories to the search path.  These directories are
  4606.     added at the front, and will therefore be searched first.
  4607.  
  4608. directory
  4609.     Reset the search path.  This requires confirmation.
  4610.  
  4611. 9.8.4 Working directory
  4612.  
  4613. Each time a program is started in the debugger, it inherits its working
  4614. directory from the current working directory of the debugger.  This working
  4615. directory is initially whatever it inherited from its parent process
  4616. (typically the shell), but you can specify a new working directory in the
  4617. debugger with the cd command or the -cd command-line option.
  4618.  
  4619.  
  4620. Chapter 9.   The debugger (camldebug)                                       78
  4621.  
  4622.  
  4623. cd directory
  4624.     Set the working directory for camldebug to directory.
  4625.  
  4626. pwd Print the working directory for camldebug.
  4627.  
  4628. 9.8.5 Module management
  4629.  
  4630. Like the Caml Light compiler, the debugger maintains a list of opened modules
  4631. in order to resolves variable name ambiguities.  The opened modules also
  4632. affect the printing of values:  whether fully qualified names or short names
  4633. are used for constructors and record labels.
  4634.   When a program is executed, the debugger automatically opens the modules of
  4635. the standard library it uses.
  4636.  
  4637. open modules
  4638.     Open the given modules.
  4639.  
  4640. close modules
  4641.     Close the given modules.
  4642.  
  4643. info modules
  4644.     List the modules used by the program, and the open modules.
  4645.  
  4646. 9.8.6 Turning reverse execution on and off
  4647.  
  4648. In some cases, you may want to turn reverse execution off.  This speeds up the
  4649. program execution, and is also sometimes useful for interactive programs.
  4650.   Normally, the debugger takes checkpoints of the program state from time to
  4651. time.  That is, it makes a copy of the current state of the program (using the
  4652. Unix system call fork).  If the variable checkpoints is set to off, the
  4653. debugger will not take any checkpoints.
  4654.  
  4655. set checkpoints on/off
  4656.     Select whether the debugger makes checkpoints or not.
  4657.  
  4658. 9.8.7 Communication between the debugger and the program
  4659.  
  4660. The debugger communicate with the program being debugged through a Unix
  4661. socket.  You may need to change the socket name, for example if you need to
  4662. run the debugger on a machine and your program on another.
  4663.  
  4664. set socket socket
  4665.     Use socket for communication with the program.  socket can be either a
  4666.     file name, or an Internet port specification host:port, where host is a
  4667.     host name or an Internet address in dot notation, and port is a port
  4668.     number on the host.
  4669.  
  4670.   On the debugged program side, the socket name is passed either by the -D
  4671. command line option to camlrun, or through the CAML_DEBUG_SOCKET environment
  4672. variable.
  4673.  
  4674. 9.8.8 Fine-tuning the debugger
  4675.  
  4676. Several variables enables to fine-tune the debugger.  Reasonable defaults are
  4677. provided, and you should normally not have to change them.
  4678.  
  4679.  
  4680. Chapter 9.   The debugger (camldebug)                                       79
  4681.  
  4682.  
  4683. set processcount count
  4684.     Set the maximum number of checkpoints to count.  More checkpoints
  4685.     facilitate going far back in time, but use more memory and create more
  4686.     Unix processes.
  4687.  
  4688.   As checkpointing is quite expensive, it must not be done too often.  On the
  4689. other hand, backward execution is faster when checkpoints are taken more
  4690. often.  In particular, backward single-stepping is more responsive when many
  4691. checkpoints have been taken just before the current time.  To fine-tune the
  4692. checkpointing strategy, the debugger does not take checkpoints at the same
  4693. frequency for long displacements (e.g.  run) and small ones (e.g.  step).  The
  4694. two variables bigstep and smallstep contain the number of events between two
  4695. checkpoints in each case.
  4696.  
  4697. set bigstep count
  4698.     Set the number of events between two checkpoints for long displacements.
  4699.  
  4700. set smallstep count
  4701.     Set the number of events between two checkpoints for small displacements.
  4702.  
  4703.   The following commands display information on checkpoints and events:
  4704.  
  4705. info checkpoints
  4706.     Print a list of checkpoints.
  4707.  
  4708. info events [module]
  4709.     Print the list of events in the given module (the current module, by
  4710.     default).
  4711.  
  4712.  
  4713. 9.9 Miscellaneous commands
  4714.  
  4715. list [module] [beginning] [end]
  4716.     List the source of module module, from line number beginning to line
  4717.     number end.  By default, 20 lines of the current module are displayed,
  4718.     starting 10 lines before the current position.
  4719.  
  4720. source filename
  4721.     Read debugger commands from the script filename.
  4722.  
  4723.  
  4724.  
  4725.  
  4726.  
  4727.  
  4728.  
  4729.  
  4730.  
  4731.  
  4732.  
  4733. Chapter 10
  4734.  
  4735.  
  4736.  
  4737. Profiling (camlpro)
  4738.  
  4739.  
  4740.  
  4741. This chapter describes how the execution of Caml Light programs can be
  4742. profiled, by recording how many times functions are called, branches of
  4743. conditionals are taken, ...
  4744.  
  4745. Mac:  This command is not available.
  4746.  
  4747. PC:   This command is not available.
  4748.  
  4749.  
  4750. 10.1 Compiling for profiling
  4751.  
  4752. Before profiling an execution, the program must be compiled in profiling mode,
  4753. using the -p option to the batch compiler camlc (see chapter 4).  When
  4754. compiling modules separately, the -p option must be given both when compiling
  4755. the modules (production of .zo files) and when linking them together.
  4756.   The amount of profiling information can be controlled by adding one or
  4757. several letters after the -p option, indicating which parts of the program
  4758. should be profiled:
  4759.  
  4760. a   all options
  4761.  
  4762. f   function calls :  a count point is set at the beginning of function
  4763.     bodies
  4764.  
  4765. i   if ...then ...else ...  :  count points are set in both then branch and
  4766.     else branch
  4767.  
  4768. l   while, for loops:  a count point is set at the beginning of the loop body
  4769.  
  4770. m   match branches:  a count point is set at the beginning of the body of
  4771.     each branch
  4772.  
  4773. t   try ...with ...  branches:  a count point is set at the beginning of the
  4774.     body of each branch
  4775.  
  4776.   For instance, compiling with -pfilm profiles function calls, if...then
  4777. ...else..., loops and pattern matching.
  4778.   The -p option without additional letters defaults to -pfm, meaning that only
  4779. function calls and pattern matching are profiled.
  4780.  
  4781.  
  4782.  
  4783.  
  4784.  
  4785.  
  4786.                                       80
  4787.  
  4788.  
  4789. Chapter 10.   Profiling (camlpro)                                           81
  4790.  
  4791.  
  4792. 10.2 Profiling an execution
  4793.  
  4794. Running a bytecode executable file that has been compiled and linked with -p
  4795. records the execution counts for the specified parts of the program and saves
  4796. them in a file called camlpro.dump in the current directory.
  4797.   More precisely, the dump file camlpro.dump is written when the io__exit
  4798. function is called.  The linker, called with the -p option, adds io__exit 0 as
  4799. the last phrase of the bytecode executable, in case the original program never
  4800. calls io__exit.  However, if the program terminates with an uncaught
  4801. exception, the dump file will not be produced.
  4802.   If a compatible dump file already exists in the current directory, then the
  4803. profiling information is accumulated in this dump file.  This allows, for
  4804. instance, the profiling of several executions of a program on different
  4805. inputs.
  4806.  
  4807.  
  4808. 10.3 Printing profiling information
  4809.  
  4810. The camlpro command produces a source listing of the program modules where
  4811. execution counts have been inserted as comments.  For instance,
  4812.  
  4813.         camlpro foo.ml
  4814.  
  4815. prints the source code for the foo module, with comments indicating how many
  4816. times the functions in this module have been called.  Naturally, this
  4817. information is accurate only if the source file has not been modified since
  4818. the profiling execution took place.
  4819.   The following options are recognized by camlpro:
  4820.  
  4821. compiler options -stdlib, -I, -include, -O, -open, -i, -lang
  4822.     See chapter 4 for the detailed usage.
  4823.  
  4824. -f dumpfile
  4825.     Specifies an alternate dump file of profiling information
  4826.  
  4827. -F string
  4828.     Specifies an additional string to be output with profiling information.
  4829.     By default, camlpro will annotate progams with comments of the form (* n
  4830.     *) where n is the counter value for a profiling point.  With option -F s,
  4831.     the annotation will be (* sn *).
  4832.  
  4833.   An additional argument specifies the output file.  For instance
  4834.  
  4835. camlpro -f ../test/camlpro.dump foo.ml foo_profiled.ml
  4836.  
  4837. will save the annotated program in file foo_profiled.ml.  Otherwise, the
  4838. annotated program is written on the standard output.
  4839.  
  4840.  
  4841. 10.4 Known bugs
  4842.  
  4843. The following situation (file x.ml)
  4844.  
  4845. let a = 1;;
  4846. x__a ;;
  4847.  
  4848. will break the profiler.  More precisely, one should avoid to refer to symbols
  4849. of the current module with the qualified symbol syntax.
  4850.  
  4851.  
  4852.  
  4853.  
  4854.  
  4855.  
  4856.  
  4857.  
  4858.  
  4859.  
  4860.  
  4861. Chapter 11
  4862.  
  4863.  
  4864.  
  4865. Using Caml Light under Emacs
  4866.  
  4867.  
  4868.  
  4869. This chapter describes how Caml Light can be used in conjunction with Gnu
  4870. Emacs version 19 (version 18 is also partially supported).
  4871.  
  4872. Unix: The Emacs Lisp files implementing the Caml/Emacs interface are in
  4873.       contrib/camlmode in the distribution.
  4874.  
  4875. Mac:  The Caml/Emacs interface is not available.
  4876.  
  4877. PC:   The Caml/Emacs interface is not available.
  4878.  
  4879.  
  4880. 11.1 Updating your .emacs
  4881.  
  4882. The following initializations must be added to your .emacs file:
  4883.  
  4884. (setq auto-mode-alist (cons '("\\.ml[iylp]?" . caml-mode) auto-mode-alist))
  4885. (autoload 'caml-mode "caml" "Major mode for editing Caml code." t)
  4886. (autoload 'run-caml "inf-caml" "Run an inferior Caml process." t)
  4887. (autoload 'camldebug "camldebug" "Run the Caml debugger." t)
  4888.  
  4889.  
  4890. 11.2 The caml editing mode
  4891.  
  4892. The caml-mode function is a major editing mode for Caml source files.  It
  4893. provides the correct syntax tables, comment syntax, ... for the Caml language.
  4894. An extremely crude indentation facility is provided, as well as a slightly
  4895. enhanced next-error command (to display the location of a compilation error).
  4896. The following key bindings are performed:
  4897.  
  4898. TAB (function caml-indent-command)
  4899.     At the beginning of a line, indent that line like the line above.
  4900.     Successive TABs increase the indentation level by 2 spaces (by default;
  4901.     can be set with the caml-mode-indentation variable).
  4902.  
  4903. M-TAB (function caml-unindent-command)
  4904.     Decrease the indentation level of the current phrase.
  4905.  
  4906. C-x ` (function caml-next-error)
  4907.     Display the next compilation error, just as next-error does.  In
  4908.     addition, it puts the point and the mark around the exact location of the
  4909.     error (the subexpression that caused the error).  Under Emacs 19, that
  4910.     subexpression is also highlighted.
  4911.  
  4912.  
  4913.  
  4914.  
  4915.                                       82
  4916.  
  4917.  
  4918. Chapter 11.   Using Caml Light under Emacs                                  83
  4919.  
  4920.  
  4921. M-C-h (function caml-mark-phrase)
  4922.     Mark the Caml phrase that contains the point:  the point is put at the
  4923.     beginning of the phrase and the mark at the end.  Phrases are delimited
  4924.     by ;; (the final double-semicolon).  This function does not properly
  4925.     ignore ;; inside string literals or comments.
  4926.  
  4927. C-x SPC
  4928.     When the Caml debugger is running as an inferior process (section 11.4
  4929.     below), set a breakpoint at the current position of the point.
  4930.  
  4931. M-C-x or C-c C-e (function caml-eval-phrase)
  4932.     When a Caml toplevel is running as an inferior process (section 11.3
  4933.     below), send it the the Caml phrase that contains the point.  The phrase
  4934.     will then be evaluated by the inferior toplevel as usual.  The phrase is
  4935.     delimited by ;; as described for the caml-mark-phrase command.
  4936.  
  4937. C-c C-r (function caml-eval-region)
  4938.     Send the region to a Caml toplevel running in an inferior process.
  4939.  
  4940.  
  4941. 11.3 Running the toplevel as an inferior process
  4942.  
  4943. M-x run-caml starts a Caml toplevel with input and output in an Emacs buffer
  4944. named *inferior-caml*.  This gives you the full power of Emacs to edit the
  4945. input to the Caml toplevel.  An history of input lines is maintained, as in
  4946. Shell mode.  This includes the following commands (see the function
  4947. comint-mode for a complete description):
  4948.  
  4949. RET Send the current line to the toplevel.
  4950.  
  4951. M-n and M-p
  4952.     Move to the next or previous line in the history.
  4953.  
  4954. M-r and M-s
  4955.     Regexp search in the history.
  4956.  
  4957. C-c C-c
  4958.     Send a break (interrupt signal) to the Caml toplevel.
  4959.  
  4960.   Phrases can also be sent to the Caml toplevel for evaluation from any buffer
  4961. in Caml mode, using M-C-x, C-c C-e or C-c C-r.
  4962.  
  4963.  
  4964. 11.4 Running the debugger as an inferior process
  4965.  
  4966. The Caml debugger is started by the command M-x camldebug, with argument the
  4967. name of the executable file progname to debug.  Communication with the
  4968. debugger takes place in an Emacs buffer named *camldebug-progname*.  The
  4969. editing and history facilities of Shell mode are available for interacting
  4970. with the debugger.
  4971.   In addition, Emacs displays the source files containing the current event
  4972. (the current position in the program execution) and highlights the location of
  4973. the event.  This display is updated synchronously with the debugger action.
  4974.   The following bindings for the most common debugger commands are available
  4975. in the *camldebug-progname* buffer (see section 9.3 for a full explanation of
  4976. the commands):
  4977.  
  4978. M-r run command:  execute the program forward.
  4979.  
  4980.  
  4981. Chapter 11.   Using Caml Light under Emacs                                  84
  4982.  
  4983.  
  4984. M-s step command:  execute the program one step forward.
  4985.  
  4986. M-b back command:  execute the program one step backward.
  4987.  
  4988. M-l last command:  go back one step in the command history.
  4989.  
  4990. C-c >
  4991.     down command:  select the stack frame below the current frame.
  4992.  
  4993. C-c <
  4994.     up command:  select the stack frame above the current frame.
  4995.  
  4996. C-c C-f
  4997.     finish command:  run till the current function returns.
  4998.  
  4999.   In a buffer in Caml editing mode, C-x SPC sets a breakpoint at the current
  5000. position of the point.
  5001.  
  5002.  
  5003.  
  5004.  
  5005.  
  5006.  
  5007.  
  5008.  
  5009.  
  5010.  
  5011.  
  5012. Chapter 12
  5013.  
  5014.  
  5015.  
  5016. Interfacing C with Caml Light
  5017.  
  5018.  
  5019.  
  5020. This chapter describes how user-defined primitives, written in C, can be added
  5021. to the Caml Light runtime system and called from Caml Light code.
  5022.  
  5023.  
  5024. 12.1 Overview and compilation information
  5025.  
  5026. 12.1.1 Declaring primitives
  5027.  
  5028. User primitives are declared in a module interface (a .mli file), in the same
  5029. way as a regular ML value, except that the declaration is followed by the =
  5030. sign, the function arity (number of arguments), and the name of the
  5031. corresponding C function.  For instance, here is how the input primitive is
  5032. declared in the interface for the standard library module io:
  5033.  
  5034.         value input : in_channel -> string -> int -> int -> int
  5035.                     = 4 "input"
  5036.  
  5037. Primitives with several arguments are always curried.  The C function does not
  5038. necessarily have the same name as the ML function.
  5039.   Values thus declared primitive in a module interface must not be implemented
  5040. in the module implementation (the .ml file).  They can be used inside the
  5041. module implementation.
  5042.  
  5043. 12.1.2 Implementing primitives
  5044.  
  5045. User primitives with arity n<5 are implemented by C functions that take n
  5046. arguments of type value, and return a result of type value.  The type value is
  5047. the type of the representations for Caml Light values.  It encodes objects of
  5048. several base types (integers, floating-point numbers, strings, ...), as well
  5049. as Caml Light data structures.  The type value and the associated conversion
  5050. functions and macros are described in details below.  For instance, here is
  5051. the declaration for the C function implementing the input primitive:
  5052.  
  5053.         value input(channel, buffer, offset, length)
  5054.                 value channel, buffer, offset, length;
  5055.         {
  5056.          ...
  5057.         }
  5058.  
  5059.   When the primitive function is applied in a Caml Light program, the C
  5060. function is called with the values of the expressions to which the primitive
  5061. is applied as arguments.  The value returned by the function is passed back to
  5062. the Caml Light program as the result of the function application.
  5063.  
  5064.  
  5065.                                       85
  5066.  
  5067.  
  5068. Chapter 12.   Interfacing C with Caml Light                                 86
  5069.  
  5070.  
  5071.   User primitives with arity greater than 5 are implemented by C functions
  5072. that receive two arguments:  a pointer to an array of Caml Light values (the
  5073. values for the arguments), and an integer which is the number of arguments
  5074. provided:
  5075.  
  5076.         value prim_with_lots_of_args(argv, argn)
  5077.                 value * argv;
  5078.                 int argn;
  5079.         {
  5080.           ... argv[0] ...;              /* The first argument */
  5081.           ... argv[6] ...;              /* The seventh argument */
  5082.         }
  5083.  
  5084.   Implementing a user primitive is actually two separate tasks:  on the one
  5085. hand, decoding the arguments to extract C values from the given Caml Light
  5086. values, and encoding the return value as a Caml Light value; on the other
  5087. hand, actually computing the result from the arguments.  Except for very
  5088. simple primitives, it is often preferable to have two distinct C functions to
  5089. implement these two tasks.  The first function actually implements the
  5090. primitive, taking native C values as arguments and returning a native C value.
  5091. The second function, often called the ``stub code'', is a simple wrapper
  5092. around the first function that converts its arguments from Caml Light values
  5093. to C values, call the first function, and convert the returned C value to Caml
  5094. Light value.  For instance, here is the stub code for the input primitive:
  5095.  
  5096.         value input(channel, buffer, offset, length)
  5097.                 value channel, buffer, offset, length;
  5098.         {
  5099.           return Val_long(getblock((struct channel *) channel,
  5100.                                    &Byte(buffer, Long_val(offset)),
  5101.                                    Long_val(length)));
  5102.         }
  5103.  
  5104. (Here, Val_long, Long_val and so on are conversion macros for the type value,
  5105. that will be described later.)  The hard work is performed by the function
  5106. getblock, which is declared as:
  5107.  
  5108.         long getblock(channel, p, n)
  5109.              struct channel * channel;
  5110.              char * p;
  5111.              long n;
  5112.         {
  5113.           ...
  5114.         }
  5115.  
  5116.   To write C code that operates on Caml Light values, the following include
  5117. files are provided:
  5118.    ------------------------------------------------------------------------
  5119.    |Include file |Provides                                                |
  5120.    ------------------------------------------------------------------------
  5121.    |mlvalues.h   |definition of the value type, and conversion macros     |
  5122.    |alloc.h      |allocation functions  (to create structured  Caml Light |
  5123.    |             |objects)                                                |
  5124.    |memory.h     |miscellaneous  memory-related functions  (for  in-place |
  5125.    |             |modification of structures, etc).                       |
  5126.    ------------------------------------------------------------------------
  5127.  
  5128. These files reside in the Caml Light standard library directory (usually
  5129. /usr/local/lib/caml-light).
  5130.  
  5131.  
  5132. Chapter 12.   Interfacing C with Caml Light                                 87
  5133.  
  5134.  
  5135. 12.1.3 Linking C code with Caml Light code
  5136.  
  5137. The Caml Light runtime system comprises three main parts:  the bytecode
  5138. interpreter, the memory manager, and a set of C functions that implement the
  5139. primitive operations.  Some bytecode instructions are provided to call these C
  5140. functions, designated by their offset in a table of functions (the table of
  5141. primitives).
  5142.   In the default mode, the Caml Light linker produces bytecode for the
  5143. standard runtime system, with a standard set of primitives.  References to
  5144. primitives that are not in this standard set result in the ``unavailable C
  5145. primitive'' error.
  5146.   In the ``custom runtime'' mode, the Caml Light linker scans the bytecode
  5147. object files (.zo files) and determines the set of required primitives.  Then,
  5148. it builds a suitable runtime system, by calling the native code linker with:
  5149.  
  5150.  -  the table of the required primitives
  5151.  
  5152.  -  a library that provides the bytecode interpreter, the memory manager, and
  5153.     the standard primitives
  5154.  
  5155.  -  libraries and object code files (.o files) mentioned on the command line
  5156.     for the Caml Light linker, that provide implementations for the user's
  5157.     primitives.
  5158.  
  5159. This builds a runtime system with the required primitives.  The Caml Light
  5160. linker generates bytecode for this custom runtime system.  The bytecode is
  5161. appended to the end of the custom runtime system, so that it will be
  5162. automatically executed when the output file (custom runtime + bytecode) is
  5163. launched.
  5164.   To link in ``custom runtime'' mode, execute the camlc command with:
  5165.  
  5166.  -  the -custom option
  5167.  
  5168.  -  the names of the desired Caml Light object files (.zo files)
  5169.  
  5170.  -  the names of the C object files and libraries (.o and .a files) that
  5171.     implement the required primitives.  (Libraries can also be specified with
  5172.     the usual -l syntax.)
  5173.  
  5174.  
  5175. 12.2 The value type
  5176.  
  5177. All Caml Light objects are represented by the C type value, defined in the
  5178. include file mlvalues.h, along with macros to manipulate values of that type.
  5179. An object of type value is either:
  5180.  
  5181.  -  an unboxed integer
  5182.  
  5183.  -  a pointer to a block inside the heap (such as the blocks allocated
  5184.     through one of the alloc_* functions below)
  5185.  
  5186.  -  a pointer to an object outside the heap (e.g., a pointer to a block
  5187.     allocated by malloc, or to a C variable).
  5188.  
  5189. 12.2.1 Integer values
  5190.  
  5191. Integer values encode 31-bit signed integers.  They are unboxed (unallocated).
  5192.  
  5193.  
  5194. Chapter 12.   Interfacing C with Caml Light                                 88
  5195.  
  5196.  
  5197. 12.2.2 Blocks
  5198.  
  5199. Blocks in the heap are garbage-collected, and therefore have strict structure
  5200. constraints.  Each block includes a header containing the size of the block
  5201. (in words), and the tag of the block.  The tag governs how the contents of the
  5202. blocks are structured.  A tag lower than No_scan_tag indicates a structured
  5203. block, containing well-formed values, which is recursively traversed by the
  5204. garbage collector.  A tag greater than or equal to No_scan_tag indicates a raw
  5205. block, whose contents are not scanned by the garbage collector.  For the
  5206. benefits of ad-hoc polymorphic primitives such as equality and structured
  5207. input-output, structured and raw blocks are further classified according to
  5208. their tags as follows:
  5209.     ---------------------------------------------------------------------
  5210.     |Tag                 |Contents of the block                          |
  5211.     ---------------------------------------------------------------------
  5212.     |0 to No_scan_tag- 1 |A  structured block  (an array  of Caml  Light |
  5213.     |                    |objects).  Each field is a value.              |
  5214.     |Closure_tag         |A  closure  representing a  functional  value. |
  5215.     |                    |The  first  word  is  a  pointer  to  a  piece |
  5216.     |                    |of  bytecode,  the  second  word  is  a  value |
  5217.     |                    |containing the environment.                    |
  5218.     |String_tag          |A character string.                            |
  5219.     |Double_tag          |A double-precision floating-point number.      |
  5220.     |Abstract_tag        |A block representing an abstract datatype.     |
  5221.     |Final_tag           |A block representing an abstract datatype with |
  5222.     |                    |a ``finalization'' function, to be called when |
  5223.     |                    |the block is deallocated.                      |
  5224.     ---------------------------------------------------------------------
  5225.  
  5226. 12.2.3 Pointers to outside the heap
  5227.  
  5228. Any pointer to outside the heap can be safely cast to and from the type value.
  5229. This includes pointers returned by malloc, and pointers to C variables
  5230. obtained with the & operator.
  5231.  
  5232.  
  5233. 12.3 Representation of Caml Light data types
  5234.  
  5235. This section describes how Caml Light data types are encoded in the value
  5236. type.
  5237.  
  5238. 12.3.1 Atomic types
  5239.               -------------------------------------------------
  5240.               |Caml type |Encoding                             |
  5241.               -------------------------------------------------
  5242.               |int       |Unboxed integer values.              |
  5243.               |char      |Unboxed integer values (ASCII code). |
  5244.               |float     |Blocks with tag Double_tag.          |
  5245.               |string    |Blocks with tag String_tag.          |
  5246.               -------------------------------------------------
  5247.  
  5248. 12.3.2 Product types
  5249.  
  5250. Tuples and arrays are represented by pointers to blocks, with tag 0.
  5251.   Records are also represented by zero-tagged blocks.  The ordering of labels
  5252. in the record type declaration determines the layout of the record fields:
  5253. the value associated to the label declared first is stored in field 0 of the
  5254. block, the value associated to the label declared next goes in field 1, and so
  5255. on.
  5256.  
  5257.  
  5258. Chapter 12.   Interfacing C with Caml Light                                 89
  5259.  
  5260.  
  5261. 12.3.3 Concrete types
  5262.  
  5263. Constructed terms are represented by blocks whose tag encode the constructor.
  5264. The constructors for a given concrete type are numbered from 0 to the number
  5265. of constructors minus one, following the order in which they appear in the
  5266. concrete type declaration.  Constant constructors are represented by
  5267. zero-sized blocks (atoms), tagged with the constructor number.  Non-constant
  5268. constructors declared with a n-tuple as argument are represented by a block of
  5269. size n, tagged with the constructor number; the n fields contain the
  5270. components of its tuple argument.  Other non-constant constructors are
  5271. represented by a block of size 1, tagged with the constructor number; the
  5272. field 0 contains the value of the constructor argument.  Example:
  5273.    ------------------------------------------------------------------------
  5274.    |Constructed term|Representation                                       |
  5275.    ------------------------------------------------------------------------
  5276.    |()              |Size = 0, tag = 0                                    |
  5277.    |false           |Size = 0, tag = 0                                    |
  5278.    |true            |Size = 0, tag = 1                                    |
  5279.    |[]              |Size = 0, tag = 0                                    |
  5280.    |h::t            |Size = 2, tag = 1, first field = h, second field = t |
  5281.    ------------------------------------------------------------------------
  5282.  
  5283. 12.4 Operations on values
  5284.  
  5285. 12.4.1 Kind tests
  5286.  
  5287.  -  Is_int(v) is true if value v is an immediate integer, false otherwise
  5288.  
  5289.  -  Is_block(v) is true if value v is a pointer to a block, and false if it
  5290.     is an immediate integer.
  5291.  
  5292. 12.4.2 Operations on integers
  5293.  
  5294.  -  Val_long(l) returns the value encoding the long int l
  5295.  
  5296.  -  Long_val(v) returns the long int encoded in value v
  5297.  
  5298.  -  Val_int(i) returns the value encoding the int i
  5299.  
  5300.  -  Int_val(v) returns the int encoded in value v
  5301.  
  5302. 12.4.3 Accessing blocks
  5303.  
  5304.  -  Wosize_val(v) returns the size of value v, in words, excluding the
  5305.     header.
  5306.  
  5307.  -  Tag_val(v) returns the tag of value v.
  5308.  
  5309.                                                    th
  5310.  -  Field(v,n) returns the value contained in the n   field of the structured
  5311.     block v.  Fields are numbered from 0 to Wosize_val(v)-1.
  5312.  
  5313.  -  Code_val(v) returns the code part of the closure v.
  5314.  
  5315.  -  Env_val(v) returns the environment part of the closure v.
  5316.  
  5317.  -  string_length(v) returns the length (number of characters) of the string
  5318.     v.
  5319.  
  5320.  
  5321. Chapter 12.   Interfacing C with Caml Light                                 90
  5322.  
  5323.  
  5324.                            th
  5325.  -  Byte(v,n) returns the n   character of the string v, with type char.
  5326.     Characters are numbered from 0 to string_length(v)-1.
  5327.  
  5328.                              th
  5329.  -  Byte_u(v,n) returns the n   character of the string v, with type unsigned
  5330.     char.  Characters are numbered from 0 to string_length(v)-1.
  5331.  
  5332.  -  String_val(v) returns a pointer to the first byte of the string v, with
  5333.     type char *.  This pointer is a valid C string:  there is a null
  5334.     character after the last character in the string.  However, Caml Light
  5335.     strings can contain embedded null characters, that will confuse the usual
  5336.     C functions over strings.
  5337.  
  5338.  -  Double_val(v) returns the floating-point number contained in value v,
  5339.     with type double.
  5340.  
  5341. The expressions Field(v,n), Code_val(v), Env_val(v), Byte(v,n), Byte_u(v,n)
  5342. and Double_val(v) are valid l-values.  Hence, they can be assigned to,
  5343. resulting in an in-place modification of value v.  Assigning directly to
  5344. Field(v,n) must be done with care to avoid confusing the garbage collector
  5345. (see below).
  5346.  
  5347. 12.4.4 Allocating blocks
  5348.  
  5349. From the standpoint of the allocation functions, blocks are divided according
  5350. to their size as zero-sized blocks, small blocks (with size less than or equal
  5351. to Max_young_wosize), and large blocks (with size greater than to
  5352. Max_young_wosize).  The constant Max_young_wosize is declared in the include
  5353. file mlvalues.h.  It is guaranteed to be at least 64 (words), so that any
  5354. block with constant size less than or equal to 64 can be assumed to be small.
  5355. For blocks whose size is computed at run-time, the size must be compared
  5356. against Max_young_wosize to determine the correct allocation procedure.
  5357.  
  5358.  -  Atom(t) returns an ``atom'' (zero-sized block) with tag t.  Zero-sized
  5359.     blocks are preallocated outside of the heap.  It is incorrect to try and
  5360.     allocate a zero-sized block using the functions below.  For instance,
  5361.     Atom(0) represents (), false and []; Atom(1) represents true.  (As a
  5362.     convenience, mlvalues.h defines the macros Val_unit, Val_false and
  5363.     Val_true.)
  5364.  
  5365.  -  alloc(n,t) returns a fresh small block of size n< Max_young_wosize words,
  5366.     with tag t.  If this block is a structured block (i.e.  if
  5367.     t<No_scan_tag), then the fields of the block (initially containing
  5368.     garbage) must be initialized with legal values (using direct assignment
  5369.     to the fields of the block) before the next allocation.
  5370.  
  5371.  -  alloc_tuple(n) returns a fresh small block of size n<Max_young_wosize
  5372.     words, with tag 0.  The fields of this block must be filled with legal
  5373.     values before the next allocation or modification.
  5374.  
  5375.  -  alloc_shr(n,t) returns a fresh block of size n, with tag t.  The size of
  5376.     the block can be greater than Max_young_wosize.  (It can also be smaller,
  5377.     but in this case it is more efficient to call alloc instead of
  5378.     alloc_shr.)  If this block is a structured block (i.e.  if
  5379.     t<No_scan_tag), then the fields of the block (initially containing
  5380.     garbage) must be initialized with legal values (using the initialize
  5381.     function described below) before the next allocation.
  5382.  
  5383.  
  5384. Chapter 12.   Interfacing C with Caml Light                                 91
  5385.  
  5386.  
  5387.  -  alloc_string(n) returns a string value of length n characters.  The
  5388.     string initially contains garbage.
  5389.  
  5390.  -  copy_string(s) returns a string value containing a copy of the
  5391.     null-terminated C string s (a char *).
  5392.  
  5393.  -  copy_double(d) returns a floating-point value initialized with the double
  5394.     d.
  5395.  
  5396.  -  alloc_array(f,a) allocates an array of values, calling function f over
  5397.     each element of the input array a to transform it into a value.  The
  5398.     array a is an array of pointers terminated by the null pointer.  The
  5399.     function f receives each pointer as argument, and returns a value.  The
  5400.     zero-tagged block returned by alloc_array(f,a) is filled with the values
  5401.     returned by the successive calls to f.
  5402.  
  5403.  -  copy_string_array(p) allocates an array of strings, copied from the
  5404.     pointer to a string array p (a char **).
  5405.  
  5406. 12.4.5 Raising exceptions
  5407.  
  5408. C functions cannot raise arbitrary exceptions.  However, two functions are
  5409. provided to raise two standard exceptions:
  5410.  
  5411.  -  failwith(s), where s is a null-terminated C string (with type char *),
  5412.     raises exception Failure with argument s.
  5413.  
  5414.  -  invalid_argument(s), where s is a null-terminated C string (with type
  5415.     char *), raises exception Invalid_argument with argument s.
  5416.  
  5417.  
  5418. 12.5 Living in harmony with the garbage collector
  5419.  
  5420. Unused blocks in the heap are automatically reclaimed by the garbage
  5421. collector.  This requires some cooperation from C code that manipulates
  5422. heap-allocated blocks.
  5423.  
  5424. Rule 1 After a structured block (a block with tag less than No_scan_tag) is
  5425. allocated, all fields of this block must be filled with well-formed values
  5426. before the next allocation operation.  If the block has been allocated with
  5427. alloc or alloc_tuple, filling is performed by direct assignment to the fields
  5428. of the block:
  5429.  
  5430.         Field(v, n) = vn;
  5431.  
  5432. If the block has been allocated with alloc_shr, filling is performed through
  5433. the initialize function:
  5434.  
  5435.         initialize(&Field(v, n), vn);
  5436.  
  5437.   The next allocation can trigger a garbage collection.  The garbage collector
  5438. assumes that all structured blocks contain well-formed values.  Newly created
  5439. blocks contain random data, which generally do not represent well-formed
  5440. values.
  5441.   If you really need to allocate before the fields can receive their final
  5442. value, first initialize with a constant value (e.g.  Val_long(0)), then
  5443. allocate, then modify the fields with the correct value (see rule 3).
  5444.  
  5445.  
  5446. Chapter 12.   Interfacing C with Caml Light                                 92
  5447.  
  5448.  
  5449. Rule 2 Local variables containing values must be registered with the garbage
  5450. collector (using the Push_roots and Pop_roots macros), if they are to survive
  5451. a call to an allocation function.
  5452.  
  5453.   Registration is performed with the Push_roots and Pop_roots macros.
  5454. Push_roots(r,n) declares an array r of n values and registers them with the
  5455. garbage collector.  The values contained in r[0] to r[n-1] are treated like
  5456. roots by the garbage collector.  A root value has the following properties:
  5457. if it points to a heap-allocated block, this block (and its contents) will not
  5458. be reclaimed; moreover, if this block is relocated by the garbage collector,
  5459. the root value is updated to point to the new location for the block.
  5460. Push_roots(r,n) must occur in a C block exactly between the last local
  5461. variable declaration and the first statement in the block.  To un-register the
  5462. roots, Pop_roots() must be called before the C block containing
  5463. Push_roots(r,n) is exited.  (Roots are automatically un-registered if a Caml
  5464. exception is raised.)
  5465.  
  5466. Rule 3 Direct assignment to a field of a block, as in
  5467.  
  5468.         Field(v, n) = w;
  5469.  
  5470. is safe only if v is a block newly allocated by alloc or alloc_tuple; that is,
  5471. if no allocation took place between the allocation of v and the assignment to
  5472. the field.  In all other cases, never assign directly.  If the block has just
  5473. been allocated by alloc_shr, use initialize to assign a value to a field for
  5474. the first time:
  5475.  
  5476.         initialize(&Field(v, n), w);
  5477.  
  5478. Otherwise, you are updating a field that previously contained a well-formed
  5479. value; then, call the modify function:
  5480.  
  5481.         modify(&Field(v, n), w);
  5482.  
  5483.   To illustrate the rules above, here is a C function that builds and returns
  5484. a list containing the two integers given as parameters:
  5485.  
  5486. value alloc_list_int(i1, i2)
  5487.         int i1, i2;
  5488. {
  5489.   value result;
  5490.   Push_roots(r, 1);
  5491.   r[0] = alloc(2, 1);                     /* Allocate a cons cell */
  5492.   Field(r[0], 0) = Val_int(i2);           /* car = the integer i2 */
  5493.   Field(r[0], 1) = Atom(0);               /* cdr = the empty list [] */
  5494.   result = alloc(2, 1);                   /* Allocate the other cons cell */
  5495.   Field(result, 0) = Val_int(i1);         /* car = the integer i1 */
  5496.   Field(result, 1) = r[0];                /* cdr = the first cons cell */
  5497.   Pop_roots();
  5498.   return result;
  5499. }
  5500.  
  5501. The ``cons'' cell allocated first needs to survive the allocation of the other
  5502. cons cell; hence, the value returned by the first call to alloc must be stored
  5503. in a registered root.  The value returned by the second call to alloc can
  5504. reside in the un-registered local variable result, since we won't do any
  5505. further allocation in this function.
  5506.  
  5507.  
  5508. Chapter 12.  Interfacing C with Caml Light                                  93
  5509.  
  5510.  
  5511.   In the example above, the list is built bottom-up.  Here is an alternate
  5512. way, that proceeds top-down.  It is less efficient, but illustrates the use of
  5513. modify.
  5514.  
  5515. value alloc_list_int(i1, i2)
  5516.         int i1, i2;
  5517. {
  5518.   value tail;
  5519.   Push_roots(r, 1);
  5520.   r[0] = alloc(2, 1);                     /* Allocate a cons cell */
  5521.   Field(r[0], 0) = Val_int(i1);           /* car = the integer i1 */
  5522.   Field(r[0], 1) = Val_int(0);            /* A dummy value
  5523.   tail = alloc(2, 1);                     /* Allocate the other cons cell */
  5524.   Field(tail, 0) = Val_int(i2);           /* car = the integer i2 */
  5525.   Field(tail, 1) = Atom(0);               /* cdr = the empty list [] */
  5526.   modify(&Field(r[0], 1), tail);          /* cdr of the result = tail */
  5527.   Pop_roots();
  5528.   return r[0];
  5529. }
  5530.  
  5531. It would be incorrect to perform Field(r[0], 1) = tail directly, because the
  5532. allocation of tail has taken place since r[0] was allocated.
  5533.  
  5534.  
  5535. 12.6 A complete example
  5536.  
  5537. This section outlines how the functions from the Unix curses library can be
  5538. made available to Caml Light programs.  First of all, here is the interface
  5539. curses.mli that declares the curses primitives and data types:
  5540.  
  5541. type window;;                   (* The type "window" remains abstract *)
  5542. value initscr: unit -> window = 1 "curses_initscr"
  5543.   and endwin: unit -> unit = 1 "curses_endwin"
  5544.   and refresh: unit -> unit = 1 "curses_refresh"
  5545.   and wrefresh : window -> unit = 1 "curses_wrefresh"
  5546.   and newwin: int -> int -> int -> int -> window = 4 "curses_newwin"
  5547.   and mvwin: window -> int -> int -> unit = 3 "curses_mvwin"
  5548.   and addch: char -> unit = 1 "curses_addch"
  5549.   and mvwaddch: window -> int -> int -> char -> unit = 4 "curses_mvwaddch"
  5550.   and addstr: string -> unit = 1 "curses_addstr"
  5551.   and mvwaddstr: window -> int -> int -> string -> unit = 4 "curses_mvwaddstr"
  5552. ;; (* lots more omitted *)
  5553.  
  5554. To compile this interface:
  5555.  
  5556.         camlc -c curses.mli
  5557.  
  5558.   To implement these functions, we just have to provide the stub code; the
  5559. core functions are already implemented in the curses library.  The stub code
  5560. file, curses.o, looks like:
  5561.  
  5562. #include <curses.h>
  5563. #include <mlvalues.h>
  5564.  
  5565. value curses_initscr(unit)
  5566.         value unit;
  5567. {
  5568.  
  5569.  
  5570. Chapter 12.  Interfacing C with Caml Light                                  94
  5571.  
  5572.  
  5573.    return  (value)  initscr();         /*  OK to  coerce  directly  from  WIN-
  5574. DOW * to value
  5575.                                    since that's a block created by malloc() */
  5576. }
  5577.  
  5578. value curses_wrefresh(win)
  5579.         value win;
  5580. {
  5581.   wrefresh((value) win);
  5582.   return Val_unit;               /* Or Atom(0) */
  5583. }
  5584.  
  5585. value curses_newwin(nlines, ncols, x0, y0)
  5586.         value nlines, ncols, x0, y0;
  5587. {
  5588.   return (value) newwin(Int_val(nlines), Int_val(ncols),
  5589.                         Int_val(x0), Int_val(y0));
  5590. }
  5591.  
  5592. value curses_addch(c)
  5593.         value c;
  5594. {
  5595.   addch(Int_val(c));            /* Characters are encoded like integers */
  5596.   return Val_unit;
  5597. }
  5598.  
  5599. value curses_addstr(s)
  5600.         value s;
  5601. {
  5602.   addstr(String_val(s));
  5603.   return Val_unit;
  5604. }
  5605.  
  5606. /* This goes on for pages. */
  5607.  
  5608. (Actually, it would be better to create a library for the stub code, with each
  5609. stub code function in a separate file, so that linking would pick only those
  5610. functions from the curses library that are actually used.)
  5611.   The file curses.c can be compiled with:
  5612.  
  5613.         cc -c -I/usr/local/lib/caml-light curses.c
  5614.  
  5615. or, even simpler,
  5616.  
  5617.         camlc -c curses.c
  5618.  
  5619. (When passed a .c file, the camlc command simply calls cc on that file, with
  5620. the right -I option.)
  5621.   Now, here is a sample Caml Light program test.ml that uses the curses
  5622. module:
  5623.  
  5624. #open "curses";;
  5625. let main_window = initscr () in
  5626. let small_window = newwin 10 5 20 10 in
  5627.   mvwaddstr main_window 10 2 "Hello";
  5628.   mvwaddstr small_window 4 3 "world";
  5629.   refresh();
  5630.   for i = 1 to 100000 do () done;
  5631.  
  5632.  
  5633. Chapter 12.   Interfacing C with Caml Light                                 95
  5634.  
  5635.  
  5636.   endwin()
  5637. ;;
  5638.  
  5639. To compile this program, run:
  5640.  
  5641.         camlc -c test.ml
  5642.  
  5643. Finally, to link everything together:
  5644.  
  5645.         camlc -custom -o test test.zo curses.o -lcurses
  5646.  
  5647.  
  5648.  
  5649.  
  5650.  
  5651.  
  5652.  
  5653.  
  5654.  
  5655.  
  5656.  
  5657.  
  5658.  
  5659.  
  5660.  
  5661.  
  5662.  
  5663.  
  5664.  
  5665.  
  5666.  
  5667.  
  5668.  
  5669.  
  5670.                                    Part IV
  5671.  
  5672.  
  5673.  
  5674.                             The Caml Light library
  5675.  
  5676.  
  5677.  
  5678.  
  5679.  
  5680.  
  5681.  
  5682.  
  5683.  
  5684.  
  5685.  
  5686.  
  5687.  
  5688.  
  5689.  
  5690.  
  5691.  
  5692.  
  5693.  
  5694.  
  5695.  
  5696.  
  5697.  
  5698.  
  5699.  
  5700.  
  5701.  
  5702.  
  5703.  
  5704.  
  5705.  
  5706.  
  5707.  
  5708.  
  5709.  
  5710.  
  5711.                                       96
  5712.  
  5713.  
  5714.  
  5715.  
  5716.  
  5717.  
  5718.  
  5719.  
  5720.  
  5721.  
  5722.  
  5723. Chapter 13
  5724.  
  5725.  
  5726.  
  5727. The core library
  5728.  
  5729.  
  5730.  
  5731. This chapter describes the functions provided by the Caml Light core library.
  5732. This library is special in two ways:
  5733.  
  5734.  -  It is automatically linked with the user's object code files by the camlc
  5735.     command (chapter 4).  Hence, the globals defined by these libraries can
  5736.     be used in standalone programs without having to add any .zo file on the
  5737.     command line for the linking phase.  Similarly, in interactive use, these
  5738.     globals can be used in toplevel phrases without having to load any .zo
  5739.     file in memory.
  5740.  
  5741.  -  The interfaces for the modules below are automatically ``opened'' when a
  5742.     compilation starts, or when the toplevel system is launched.  Hence, it
  5743.     is possible to use unqualified identifiers to refer to the functions
  5744.     provided by these modules, without adding #open directives.  Actually,
  5745.     the list of automatically opened modules depend on the -O option given to
  5746.     the compiler or to the toplevel system:
  5747.  
  5748.           --------------------------------------------------------------
  5749.           |-O option             |Opened   modules  (reverse   opening |
  5750.           |                      |order)                               |
  5751.           --------------------------------------------------------------
  5752.           |-O cautious (default) |io,  eq,  int,   float,  ref,  pair, |
  5753.           |                      |list, vect, char, string, bool, exc, |
  5754.           |                      |stream, builtin                      |
  5755.           |-O fast               |io, eq, int, float, ref, pair, list, |
  5756.           |                      |fvect,  fchar, fstring,  bool,  exc, |
  5757.           |                      |stream, builtin                      |
  5758.           |-O none               |builtin                              |
  5759.           --------------------------------------------------------------
  5760.  
  5761.  
  5762. Conventions
  5763.  
  5764. For easy reference, the modules are listed below in alphabetical order of
  5765. module names.  For each module, the declarations from its interface file are
  5766. printed one by one in typewriter font, followed by a short comment.  All
  5767. modules and the identifiers they export are indexed at the end of this report.
  5768.  
  5769.  
  5770. 13.1 bool:  boolean operations
  5771.  
  5772.     The boolean and is written e1 & e2.  The boolean or is written e1 or e2.
  5773.     Both constructs are sequential, left-to-right:  e2 is evaluated only if
  5774.     needed.  Actually, e1 & e2 is equivalent to if e1 then e2 else false, and
  5775.     e1 or e2 is equivalent to if e1 then true else e2.
  5776.  
  5777.  
  5778.                                       97
  5779.  
  5780.  
  5781. Chapter 13.   The core library                                              98
  5782.  
  5783.  
  5784. value prefix not : bool -> bool
  5785.  
  5786.     The boolean negation.
  5787.  
  5788. value string_of_bool : bool -> string
  5789.  
  5790.     Return a string representing the given boolean.
  5791.  
  5792.  
  5793.  
  5794. 13.2 builtin:  base types and constructors
  5795.  
  5796.     This module defines some types and exceptions for which the language
  5797.     provides special syntax, and are therefore treated specially by the
  5798.     compiler.
  5799.  
  5800. type int
  5801. type float
  5802. type string
  5803. type char
  5804.  
  5805.     The types of integers, floating-point numbers, character strings, and
  5806.     characters, respectively.
  5807.  
  5808. type exn
  5809.  
  5810.     The type of exception values.
  5811.  
  5812. type bool = false | true
  5813.  
  5814.     The type of boolean values.
  5815.  
  5816. type 'a vect
  5817.  
  5818.     The type of arrays whose elements have type 'a.
  5819.  
  5820. type unit = ()
  5821.  
  5822.     The type of the unit value.
  5823.  
  5824. type 'a list = [] | prefix :: of 'a * 'a list
  5825.  
  5826.     The type of lists.
  5827.  
  5828. exception Match_failure of string * int * int
  5829.  
  5830.     The exception raised when a pattern-matching fails.  The argument
  5831.     indicates the position in the source code of the pattern-matching (source
  5832.     file name, position of the first character of the matching, position of
  5833.     the last character.
  5834.  
  5835.  
  5836.  
  5837. 13.3 char:  character operations
  5838.  
  5839. value int_of_char : char -> int
  5840.  
  5841.     Return the ASCII code of the argument.
  5842.  
  5843.  
  5844. Chapter 13.   The core library                                              99
  5845.  
  5846.  
  5847. value char_of_int : int -> char
  5848.  
  5849.     Return the character with the given ASCII code.  Raise
  5850.     Invalid_argument "char_of_int" if the argument is outside the range
  5851.     0--255.
  5852.  
  5853. value char_for_read : char -> string
  5854.  
  5855.     Return a string representing the given character, with special characters
  5856.     escaped following the lexical conventions of Caml Light.
  5857.  
  5858.  
  5859.  
  5860. 13.4 eq:  generic comparisons
  5861.  
  5862. value prefix = : 'a -> 'a -> bool
  5863.  
  5864.     e1 = e2 tests for structural equality of e1 and e2.  Mutable structures
  5865.     (e.g.  references and arrays) are equal if and only if their current
  5866.     contents are structurally equal, even if the two mutable objects are not
  5867.     the same physical object.  Equality between functional values raises
  5868.     Invalid_argument.  Equality between cyclic data structures may not
  5869.     terminate.
  5870.  
  5871. value prefix <> : 'a -> 'a -> bool
  5872.  
  5873.     Negation of prefix =.
  5874.  
  5875. value prefix < : 'a -> 'a -> bool
  5876. value prefix <= : 'a -> 'a -> bool
  5877. value prefix > : 'a -> 'a -> bool
  5878. value prefix >= : 'a -> 'a -> bool
  5879.  
  5880.     Structural ordering functions.  These functions coincide with the usual
  5881.     orderings over integer, string and floating-point numbers, and extend
  5882.     them to a total ordering over all types.  The ordering is compatible with
  5883.     prefix =.  As in the case of prefix =, mutable structures are compared by
  5884.     contents.  Comparison between functional values raises Invalid_argument.
  5885.     Comparison between cyclic structures may not terminate.
  5886.  
  5887. value compare: 'a -> 'a -> int
  5888.  
  5889.     compare x y returns 0 if x=y, a negative integer if x<y, and a positive
  5890.     integer if x>y.  The same restrictions as for = apply.  compare can be
  5891.     used as the comparison function required by the set and map modules.
  5892.  
  5893. value min: 'a -> 'a -> 'a
  5894.  
  5895.     Return the smaller of the two arguments.
  5896.  
  5897. value max: 'a -> 'a -> 'a
  5898.  
  5899.     Return the greater of the two arguments.
  5900.  
  5901. value prefix == : 'a -> 'a -> bool
  5902.  
  5903.     e1 == e2 tests for physical equality of e1 and e2.  On integers and
  5904.     characters, it is the same as structural equality.  On mutable
  5905.  
  5906.  
  5907. Chapter 13.   The core library                                             100
  5908.  
  5909.  
  5910.     structures, e1 == e2 is true if and only if physical modification of e1
  5911.     also affects e2.  On non-mutable structures, the behavior of prefix == is
  5912.     implementation-dependent, except that e1 == e2 implies e1 = e2.
  5913.  
  5914. value prefix != : 'a -> 'a -> bool
  5915.  
  5916.     Negation of prefix ==.
  5917.  
  5918.  
  5919.  
  5920. 13.5 exc:  exceptions
  5921.  
  5922. value raise : exn -> 'a
  5923.  
  5924.     Raise the given exception value.
  5925.  
  5926.  
  5927. A few general-purpose predefined exceptions.
  5928.  
  5929. exception Out_of_memory
  5930.  
  5931.     Raised by the garbage collector, when there is insufficient memory to
  5932.     complete the computation.
  5933.  
  5934. exception Invalid_argument of string
  5935.  
  5936.     Raised by library functions to signal that the given arguments do not
  5937.     make sense.
  5938.  
  5939. exception Failure of string
  5940.  
  5941.     Raised by library functions to signal that they are undefined on the
  5942.     given arguments.
  5943.  
  5944. exception Not_found
  5945.  
  5946.     Raised by search functions when the desired object could not be found.
  5947.  
  5948. exception Exit
  5949.  
  5950.     This exception is not raised by any library function.  It is provided for
  5951.     use in your programs.
  5952.  
  5953. value failwith : string -> 'a
  5954.  
  5955.     Raise exception Failure with the given string.
  5956.  
  5957. value invalid_arg : string -> 'a
  5958.  
  5959.     Raise exception Invalid_argument with the given string.
  5960.  
  5961.  
  5962.  
  5963. 13.6 fchar:  character operations, without sanity checks
  5964.  
  5965.     This module implements the same functions as the char module, but does
  5966.     not perform bound checks on the arguments of the functions.  The
  5967.     functions are therefore faster than those in the char module, but calling
  5968.     these functions with incorrect parameters (that is, parameters that would
  5969.  
  5970.  
  5971. Chapter 13.   The core library                                             101
  5972.  
  5973.  
  5974.     cause the Invalid_argument exception to be raised by the corresponding
  5975.     functions in the char module) can crash the program.
  5976.  
  5977.  
  5978.  
  5979. 13.7 float:  operations on floating-point numbers
  5980.  
  5981. value int_of_float : float -> int
  5982.  
  5983.     Truncate the given float to an integer value.  The result is unspecified
  5984.     if it falls outside the range of representable integers.
  5985.  
  5986. value float_of_int : int -> float
  5987.  
  5988.     Convert an integer to floating-point.
  5989.  
  5990. value minus : float -> float
  5991. value minus_float : float -> float
  5992.  
  5993.     Unary negation.
  5994.  
  5995. value prefix + : float -> float -> float
  5996. value prefix +. : float -> float -> float
  5997. value add_float : float -> float -> float
  5998.  
  5999.     Addition.
  6000.  
  6001. value prefix - : float -> float -> float
  6002. value prefix -. : float -> float -> float
  6003. value sub_float : float -> float -> float
  6004.  
  6005.     Subtraction.
  6006.  
  6007. value prefix * : float -> float -> float
  6008. value prefix *. : float -> float -> float
  6009. value mult_float : float -> float -> float
  6010.  
  6011.     Product.
  6012.  
  6013. value prefix / : float -> float -> float
  6014. value prefix /. : float -> float -> float
  6015. value div_float : float -> float -> float
  6016.  
  6017.     Division.  Raise Division_by_zero if the dividend is 0.0.
  6018.  
  6019. value prefix ** : float -> float -> float
  6020. value prefix **. : float -> float -> float
  6021. value power : float -> float -> float
  6022.  
  6023.     Exponentiation.
  6024.  
  6025. value eq_float : float -> float -> bool
  6026. value prefix =. : float -> float -> bool
  6027.  
  6028.     Floating-point equality.  Equivalent to generic equality, just faster.
  6029.  
  6030. value neq_float : float -> float -> bool
  6031. value prefix <>. : float -> float -> bool
  6032.  
  6033.  
  6034. Chapter 13.   The core library                                             102
  6035.  
  6036.  
  6037.     Negation of eq_float.
  6038.  
  6039. value prefix <. : float -> float -> bool
  6040. value lt_float : float -> float -> bool
  6041. value prefix >. : float -> float -> bool
  6042. value gt_float : float -> float -> bool
  6043. value prefix <=. : float -> float -> bool
  6044. value le_float : float -> float -> bool
  6045. value prefix >=. : float -> float -> bool
  6046. value ge_float : float -> float -> bool
  6047.  
  6048.     Usual comparisons between floating-point numbers.
  6049.  
  6050. value exp : float -> float
  6051. value log : float -> float
  6052. value sqrt : float -> float
  6053. value sin : float -> float
  6054. value cos : float -> float
  6055. value tan : float -> float
  6056. value asin : float -> float
  6057. value acos : float -> float
  6058. value atan : float -> float
  6059. value atan2 : float -> float -> float
  6060.  
  6061.     Usual transcendental functions on floating-point numbers.
  6062.  
  6063. value abs_float : float -> float
  6064.  
  6065.     Return the absolute value of the argument.
  6066.  
  6067. value string_of_float : float -> string
  6068.  
  6069.     Convert the given float to its decimal representation.
  6070.  
  6071. value float_of_string : string -> float
  6072.  
  6073.     Convert the given string to a float, in decimal.  The result is
  6074.     unspecified if the given string is not a valid representation of a float.
  6075.  
  6076.  
  6077.  
  6078. 13.8 fstring:  string operations, without sanity checks
  6079.  
  6080.     This module implements the same functions as the string module, but does
  6081.     not perform bound checks on the arguments of the functions.  The
  6082.     functions are therefore faster than those in the string module, but
  6083.     calling these functions with incorrect parameters (that is, parameters
  6084.     that would cause the Invalid_argument exception to be raised by the
  6085.     corresponding functions in the string module) can crash the program.
  6086.  
  6087.  
  6088.  
  6089. 13.9 fvect:  operations on vectors, without sanity checks
  6090.  
  6091.     This module implements the same functions as the vect module, but does
  6092.     not perform bound checks on the arguments of the functions.  The
  6093.     functions are therefore faster than those in the vect module, but calling
  6094.     these functions with incorrect parameters (that is, parameters that would
  6095.  
  6096.  
  6097. Chapter 13.   The core library                                             103
  6098.  
  6099.  
  6100.     cause the Invalid_argument exception to be raised by the corresponding
  6101.     functions in the vect module) can crash the program.
  6102.  
  6103.  
  6104.  
  6105. 13.10 int:  operations on integers
  6106.  
  6107.     Integers are 31 bits wide (or 63 bits on 64-bit processors).  All
  6108.                                  31      63
  6109.     operations are taken modulo 2   (or 2  ).  They do not fail on overflow.
  6110.  
  6111. exception Division_by_zero
  6112. value minus : int -> int
  6113. value minus_int : int -> int
  6114.  
  6115.     Unary negation.  You can write -e instead of minus e.
  6116.  
  6117. value succ : int -> int
  6118.  
  6119.     succ x is x+1.
  6120.  
  6121. value pred : int -> int
  6122.  
  6123.     pred x is x-1.
  6124.  
  6125. value prefix + : int -> int -> int
  6126. value add_int : int -> int -> int
  6127.  
  6128.     Addition.
  6129.  
  6130. value prefix - : int -> int -> int
  6131. value sub_int : int -> int -> int
  6132.  
  6133.     Subtraction.
  6134.  
  6135. value prefix * : int -> int -> int
  6136. value mult_int : int -> int -> int
  6137.  
  6138.     Multiplication.
  6139.  
  6140. value prefix / : int -> int -> int
  6141. value div_int : int -> int -> int
  6142. value prefix quo : int -> int -> int
  6143.  
  6144.     Integer division.  Raise Division_by_zero if the second argument is 0.
  6145.     Give unpredictable results if either argument is negative.
  6146.  
  6147. value prefix mod : int -> int -> int
  6148.  
  6149.     Remainder.  Raise Division_by_zero if the second argument is 0.  Give
  6150.     unpredictable results if either argument is negative.
  6151.  
  6152. value eq_int : int -> int -> bool
  6153.  
  6154.     Integer equality.  Equivalent to generic equality, just faster.
  6155.  
  6156. value neq_int : int -> int -> bool
  6157.  
  6158.  
  6159. Chapter 13.   The core library                                             104
  6160.  
  6161.  
  6162.     Negation of eq_int.
  6163.  
  6164. value lt_int : int -> int -> bool
  6165. value gt_int : int -> int -> bool
  6166. value le_int : int -> int -> bool
  6167. value ge_int : int -> int -> bool
  6168.  
  6169.     Usual comparisons between integers.
  6170.  
  6171. value abs : int -> int
  6172.  
  6173.     Return the absolute value of the argument.
  6174.  
  6175.  
  6176. Bitwise operations
  6177.  
  6178. value prefix land : int -> int -> int
  6179.  
  6180.     Bitwise logical and.
  6181.  
  6182. value prefix lor : int -> int -> int
  6183.  
  6184.     Bitwise logical or.
  6185.  
  6186. value prefix lxor : int -> int -> int
  6187.  
  6188.     Bitwise logical exclusive or.
  6189.  
  6190. value lnot : int -> int
  6191.  
  6192.     Bitwise complement
  6193.  
  6194. value prefix lsl : int -> int -> int
  6195. value lshift_left : int -> int -> int
  6196.  
  6197.     n lsl m, or equivalently lshift_left n m, shifts n to the left by m bits.
  6198.  
  6199. value prefix lsr : int -> int -> int
  6200.  
  6201.     n lsr m shifts n to the right by m bits.  This is a logical shift:
  6202.     zeroes are inserted regardless of sign.
  6203.  
  6204. value prefix asr : int -> int -> int
  6205. value lshift_right : int -> int -> int
  6206.  
  6207.     n asr m, or equivalently lshift_right n m, shifts n to the right by m
  6208.     bits.  This is an arithmetic shift:  the sign bit is replicated.
  6209.  
  6210.  
  6211. Conversion functions
  6212.  
  6213. value string_of_int : int -> string
  6214.  
  6215.     Convert the given integer to its decimal representation.
  6216.  
  6217. value int_of_string : string -> int
  6218.  
  6219.  
  6220. Chapter 13.  The core library                                              105
  6221.  
  6222.  
  6223.     Convert the given string to an integer, in decimal (by default) or in
  6224.     hexadecimal, octal or binary if the string begins with 0x, 0o or 0b.
  6225.     Raise Failure "int_of_string" if the given string is not a valid
  6226.     representation of an integer.
  6227.  
  6228.  
  6229.  
  6230. 13.11 io:  buffered input and output
  6231.  
  6232. type in_channel
  6233. type out_channel
  6234.  
  6235.     The abstract types of input channels and output channels.
  6236.  
  6237. exception End_of_file
  6238.  
  6239.     Raised when an operation cannot complete, because the end of the file has
  6240.     been reached.
  6241.  
  6242. value stdin : in_channel
  6243. value std_in : in_channel
  6244. value stdout : out_channel
  6245. value std_out : out_channel
  6246. value stderr : out_channel
  6247. value std_err : out_channel
  6248.  
  6249.     The standard input, standard output, and standard error output for the
  6250.     process.  std_in, std_out and std_err are respectively synonymous with
  6251.     stdin, stdout and stderr.
  6252.  
  6253. value exit : int -> 'a
  6254.  
  6255.     Flush all pending writes on std_out and std_err, and terminate the
  6256.     process, returning the given status code to the operating system (usually
  6257.     0 to indicate no errors, and a small positive integer to indicate
  6258.     failure.)  This function should be called at the end of all standalone
  6259.     programs that output results on std_out or std_err; otherwise, the
  6260.     program may appear to produce no output, or its output may be truncated.
  6261.  
  6262.  
  6263. Output functions on standard output
  6264.  
  6265. value print_char : char -> unit
  6266.  
  6267.     Print the character on standard output.
  6268.  
  6269. value print_string : string -> unit
  6270.  
  6271.     Print the string on standard output.
  6272.  
  6273. value print_int : int -> unit
  6274.  
  6275.     Print the integer, in decimal, on standard output.
  6276.  
  6277. value print_float : float -> unit
  6278.  
  6279.     Print the floating-point number, in decimal, on standard output.
  6280.  
  6281.  
  6282. Chapter 13.  The core library                                              106
  6283.  
  6284.  
  6285. value print_endline : string -> unit
  6286.  
  6287.     Print the string, followed by a newline character, on standard output.
  6288.  
  6289. value print_newline : unit -> unit
  6290.  
  6291.     Print a newline character on standard output, and flush standard output.
  6292.     This can be used to simulate line buffering of standard output.
  6293.  
  6294.  
  6295. Output functions on standard error
  6296.  
  6297. value prerr_char : char -> unit
  6298.  
  6299.     Print the character on standard error.
  6300.  
  6301. value prerr_string : string -> unit
  6302.  
  6303.     Print the string on standard error.
  6304.  
  6305. value prerr_int : int -> unit
  6306.  
  6307.     Print the integer, in decimal, on standard error.
  6308.  
  6309. value prerr_float : float -> unit
  6310.  
  6311.     Print the floating-point number, in decimal, on standard error.
  6312.  
  6313. value prerr_endline : string -> unit
  6314.  
  6315.     Print the string, followed by a newline character on standard error and
  6316.     flush standard error.
  6317.  
  6318.  
  6319. Input functions on standard input
  6320.  
  6321. value read_line : unit -> string
  6322.  
  6323.     Flush standard output, then read characters from standard input until a
  6324.     newline character is encountered.  Return the string of all characters
  6325.     read, without the newline character at the end.
  6326.  
  6327. value read_int : unit -> int
  6328.  
  6329.     Flush standard output, then read one line from standard input and convert
  6330.     it to an integer.  Raise Failure "int_of_string" if the line read is not
  6331.     a valid representation of an integer.
  6332.  
  6333. value read_float : unit -> float
  6334.  
  6335.     Flush standard output, then read one line from standard input and convert
  6336.     it to a floating-point number.  The result is unspecified if the line
  6337.     read is not a valid representation of a floating-point number.
  6338.  
  6339.  
  6340. Chapter 13.   The core library                                             107
  6341.  
  6342.  
  6343. General output functions
  6344.  
  6345. value open_out : string -> out_channel
  6346.  
  6347.     Open the named file for writing, and return a new output channel on that
  6348.     file, positionned at the beginning of the file.  The file is truncated to
  6349.     zero length if it already exists.  It is created if it does not already
  6350.     exists.  Raise sys__Sys_error if the file could not be opened.
  6351.  
  6352. value open_out_bin : string -> out_channel
  6353.  
  6354.     Same as open_out, but the file is opened in binary mode, so that no
  6355.     translation takes place during writes.  On operating systems that do not
  6356.     distinguish between text mode and binary mode, this function behaves like
  6357.     open_out.
  6358.  
  6359. value open_out_gen : sys__open_flag list -> int -> string -> out_channel
  6360.  
  6361.     open_out_gen mode rights filename opens the file named filename for
  6362.     writing, as above.  The extra argument mode specify the opening mode (see
  6363.     sys__open).  The extra argument rights specifies the file permissions, in
  6364.     case the file must be created (see sys__open).  open_out and open_out_bin
  6365.     are special cases of this function.
  6366.  
  6367. value open_descriptor_out : int -> out_channel
  6368.  
  6369.     open_descriptor_out fd returns a buffered output channel writing to the
  6370.     file descriptor fd.  The file descriptor fd must have been previously
  6371.     opened for writing, else the behavior is undefined.
  6372.  
  6373. value flush : out_channel -> unit
  6374.  
  6375.     Flush the buffer associated with the given output channel, performing all
  6376.     pending writes on that channel.  Interactive programs must be careful
  6377.     about flushing std_out and std_err at the right time.
  6378.  
  6379. value output_char : out_channel -> char -> unit
  6380.  
  6381.     Write the character on the given output channel.
  6382.  
  6383. value output_string : out_channel -> string -> unit
  6384.  
  6385.     Write the string on the given output channel.
  6386.  
  6387. value output : out_channel -> string -> int -> int -> unit
  6388.  
  6389.     output chan buff ofs len writes len characters from string buff, starting
  6390.     at offset ofs, to the output channel chan.  Raise
  6391.     Invalid_argument "output" if ofs and len do not designate a valid
  6392.     substring of buff.
  6393.  
  6394. value output_byte : out_channel -> int -> unit
  6395.  
  6396.     Write one 8-bit integer (as the single character with that code) on the
  6397.     given output channel.  The given integer is taken modulo 256.
  6398.  
  6399.  
  6400. Chapter 13.   The core library                                             108
  6401.  
  6402.  
  6403. value output_binary_int : out_channel -> int -> unit
  6404.  
  6405.     Write one integer in binary format on the given output channel.  The only
  6406.     reliable way to read it back is through the input_binary_int function.
  6407.     The format is compatible across all machines for a given version of Caml
  6408.     Light.
  6409.  
  6410. value output_value : out_channel -> 'a -> unit
  6411.  
  6412.     Write the representation of a structured value of any type to a channel.
  6413.     Circularities and sharing inside the value are detected and preserved.
  6414.     The object can be read back, by the function input_value.  The format is
  6415.     compatible across all machines for a given version of Caml Light.
  6416.  
  6417. value output_compact_value : out_channel -> 'a -> unit
  6418.  
  6419.     Same as output_value, but uses a different format, which occupies less
  6420.     space on the file, but takes more time to generate and read back.
  6421.  
  6422. value seek_out : out_channel -> int -> unit
  6423.  
  6424.     seek_out chan pos sets the current writing position to pos for channel
  6425.     chan.  This works only for regular files.  On files of other kinds (such
  6426.     as terminals, pipes and sockets), the behavior is unspecified.
  6427.  
  6428. value pos_out : out_channel -> int
  6429.  
  6430.     Return the current writing position for the given channel.
  6431.  
  6432. value out_channel_length : out_channel -> int
  6433.  
  6434.     Return the total length (number of characters) of the given channel.
  6435.     This works only for regular files.  On files of other kinds, the result
  6436.     is meaningless.
  6437.  
  6438. value close_out : out_channel -> unit
  6439.  
  6440.     Close the given channel, flushing all buffered write operations.  The
  6441.     behavior is unspecified if any of the functions above is called on a
  6442.     closed channel.
  6443.  
  6444.  
  6445. General input functions
  6446.  
  6447. value open_in : string -> in_channel
  6448.  
  6449.     Open the named file for reading, and return a new input channel on that
  6450.     file, positionned at the beginning of the file.  Raise sys__Sys_error if
  6451.     the file could not be opened.
  6452.  
  6453. value open_in_bin : string -> in_channel
  6454.  
  6455.     Same as open_in, but the file is opened in binary mode, so that no
  6456.     translation takes place during reads.  On operating systems that do not
  6457.     distinguish between text mode and binary mode, this function behaves like
  6458.     open_in.
  6459.  
  6460.  
  6461. Chapter 13.   The core library                                             109
  6462.  
  6463.  
  6464. value open_in_gen : sys__open_flag list -> int -> string -> in_channel
  6465.  
  6466.     open_in_gen mode rights filename opens the file named filename for
  6467.     reading, as above.  The extra arguments mode and rights specify the
  6468.     opening mode and file permissions (see sys__open).  open_in and
  6469.     open_in_bin are special cases of this function.
  6470.  
  6471. value open_descriptor_in : int -> in_channel
  6472.  
  6473.     open_descriptor_in fd returns a buffered input channel reading from the
  6474.     file descriptor fd.  The file descriptor fd must have been previously
  6475.     opened for reading, else the behavior is undefined.
  6476.  
  6477. value input_char : in_channel -> char
  6478.  
  6479.     Read one character from the given input channel.  Raise End_of_file if
  6480.     there are no more characters to read.
  6481.  
  6482. value input_line : in_channel -> string
  6483.  
  6484.     Read characters from the given input channel, until a newline character
  6485.     is encountered.  Return the string of all characters read, without the
  6486.     newline character at the end.  Raise End_of_file if the end of the file
  6487.     is reached at the beginning of line.
  6488.  
  6489. value input : in_channel -> string -> int -> int -> int
  6490.  
  6491.     input chan buff ofs len attempts to read len characters from channel
  6492.     chan, storing them in string buff, starting at character number ofs.  It
  6493.     returns the actual number of characters read, between 0 and len
  6494.     (inclusive).  A return value of 0 means that the end of file was reached.
  6495.     A return value between 0 and len exclusive means that no more characters
  6496.     were available at that time; input must be called again to read the
  6497.     remaining characters, if desired.  Exception Invalid_argument "input" is
  6498.     raised if ofs and len do not designate a valid substring of buff.
  6499.  
  6500. value really_input : in_channel -> string -> int -> int -> unit
  6501.  
  6502.     really_input chan buff ofs len reads len characters from channel chan,
  6503.     storing them in string buff, starting at character number ofs.  Raise
  6504.     End_of_file if the end of file is reached before len characters have been
  6505.     read.  Raise Invalid_argument "really_input" if ofs and len do not
  6506.     designate a valid substring of buff.
  6507.  
  6508. value input_byte : in_channel -> int
  6509.  
  6510.     Same as input_char, but return the 8-bit integer representing the
  6511.     character.  Raise End_of_file if an end of file was reached.
  6512.  
  6513. value input_binary_int : in_channel -> int
  6514.  
  6515.     Read an integer encoded in binary format from the given input channel.
  6516.     See output_binary_int.  Raise End_of_file if an end of file was reached
  6517.     while reading the integer.
  6518.  
  6519. value input_value : in_channel -> 'a
  6520.  
  6521.  
  6522. Chapter 13.   The core library                                             110
  6523.  
  6524.  
  6525.     Read the representation of a structured value, as produced by
  6526.     output_value or output_compact_value, and return the corresponding value.
  6527.     This is not type-safe.  The type of the returned object is not 'a
  6528.     properly speaking:  the returned object has one unique type, which cannot
  6529.     be determined at compile-time.  The programmer should explicitly give the
  6530.     expected type of the returned value, using the following syntax:
  6531.     (input_value chan : type).  The behavior is unspecified if the object in
  6532.     the file does not belong to the given type.
  6533.  
  6534. value seek_in : in_channel -> int -> unit
  6535.  
  6536.     seek_in chan pos sets the current reading position to pos for channel
  6537.     chan.  This works only for regular files.  On files of other kinds, the
  6538.     behavior is unspecified.
  6539.  
  6540. value pos_in : in_channel -> int
  6541.  
  6542.     Return the current reading position for the given channel.
  6543.  
  6544. value in_channel_length : in_channel -> int
  6545.  
  6546.     Return the total length (number of characters) of the given channel.
  6547.     This works only for regular files.  On files of other kinds, the result
  6548.     is meaningless.
  6549.  
  6550. value close_in : in_channel -> unit
  6551.  
  6552.     Close the given channel.  Anything can happen if any of the functions
  6553.     above is called on a closed channel.
  6554.  
  6555.  
  6556.  
  6557. 13.12 list:  operations on lists
  6558.  
  6559. value list_length : 'a list -> int
  6560.  
  6561.     Return the length (number of elements) of the given list.
  6562.  
  6563. value prefix @ : 'a list -> 'a list -> 'a list
  6564.  
  6565.     List concatenation.
  6566.  
  6567. value hd : 'a list -> 'a
  6568.  
  6569.     Return the first element of the given list.  Raise Failure "hd" if the
  6570.     list is empty.
  6571.  
  6572. value tl : 'a list -> 'a list
  6573.  
  6574.     Return the given list without its first element.  Raise Failure "tl" if
  6575.     the list is empty.
  6576.  
  6577. value rev : 'a list -> 'a list
  6578.  
  6579.     List reversal.
  6580.  
  6581. value map : ('a -> 'b) -> 'a list -> 'b list
  6582.  
  6583.  
  6584. Chapter 13.   The core library                                             111
  6585.  
  6586.  
  6587.     map f [a1; ...; an] applies function f to a1, ..., an, and builds the
  6588.     list [f a1; ...; f an] with the results returned by f.
  6589.  
  6590. value do_list : ('a -> 'b) -> 'a list -> unit
  6591.  
  6592.     do_list f [a1; ...; an] applies function f in turn to a1; ...; an,
  6593.     discarding all the results.  It is equivalent to
  6594.     begin f a1; f a2; ...; f an; () end.
  6595.  
  6596. value it_list : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a
  6597.  
  6598.     it_list f a [b1; ...; bn] is f (... (f (f a b1) b2) ...) bn.
  6599.  
  6600. value list_it : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b
  6601.  
  6602.     list_it f [a1; ...; an] b is f a1 (f a2 (... (f an b) ...)).
  6603.  
  6604. value map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
  6605.  
  6606.     map2 f [a1; ...; an] [b1; ...; bn] is [f a1 b1; ...; f an bn].  Raise
  6607.     Invalid_argument "map2" if the two lists have different lengths.
  6608.  
  6609. value do_list2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> unit
  6610.  
  6611.     do_list2 f [a1; ...; an] [b1; ...; bn] calls in turn
  6612.     f a1 b1; ...; f an bn, discarding the results.  Raise
  6613.     Invalid_argument "do_list2" if the two lists have different lengths.
  6614.  
  6615. value it_list2 : ('a -> 'b -> 'c -> 'a) -> 'a -> 'b list -> 'c list -> 'a
  6616.  
  6617.     it_list2 f a [b1; ...; bn] [c1; ...; cn] is
  6618.     f (... (f (f a b1 c1) b2 c2) ...) bn cn.  Raise
  6619.     Invalid_argument "it_list2" if the two lists have different lengths.
  6620.  
  6621. value list_it2 : ('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> 'c -> 'c
  6622.  
  6623.     list_it2 f [a1; ...; an] [b1; ...; bn] c is
  6624.     f a1 b1 (f a2 b2 (... (f an bn c) ...)).  Raise
  6625.     Invalid_argument "list_it2" if the two lists have different lengths.
  6626.  
  6627. value flat_map : ('a -> 'b list) -> 'a list -> 'b list
  6628.  
  6629.     flat_map f [l1; ...; ln] is (f l1) @ (f l2) @ ... @ (f ln).
  6630.  
  6631. value for_all : ('a -> bool) -> 'a list -> bool
  6632.  
  6633.     for_all p [a1; ...; an] is (p a1) & (p a2) & ... & (p an).
  6634.  
  6635. value exists : ('a -> bool) -> 'a list -> bool
  6636.  
  6637.     exists p [a1; ...; an] is (p a1) or (p a2) or ... or (p an).
  6638.  
  6639. value mem : 'a -> 'a list -> bool
  6640.  
  6641.     mem a l is true if and only if a is structurally equal (see module eq) to
  6642.     an element of l.
  6643.  
  6644.  
  6645. Chapter 13.   The core library                                             112
  6646.  
  6647.  
  6648. value memq : 'a -> 'a list -> bool
  6649.  
  6650.     memq a l is true if and only if a is physically equal (see module eq) to
  6651.     an element of l.
  6652.  
  6653. value except : 'a -> 'a list -> 'a list
  6654.  
  6655.     except a l returns the list l where the first element structurally equal
  6656.     to a has been removed.  The list l is returned unchanged if it does not
  6657.     contain a.
  6658.  
  6659. value exceptq : 'a -> 'a list -> 'a list
  6660.  
  6661.     Same as except, with physical equality instead of structural equality.
  6662.  
  6663. value subtract : 'a list -> 'a list -> 'a list
  6664.  
  6665.     subtract l1 l2 returns the list l1 where all elements structurally equal
  6666.     to one of the elements of l2 have been removed.
  6667.  
  6668. value union : 'a list -> 'a list -> 'a list
  6669.  
  6670.     union l1 l2 appends before list l2 all the elements of list l1 that are
  6671.     not structurally equal to an element of l2.
  6672.  
  6673. value intersect : 'a list -> 'a list -> 'a list
  6674.  
  6675.     intersect l1 l2 returns the list of the elements of l1 that are
  6676.     structurally equal to an element of l2.
  6677.  
  6678. value index : 'a -> 'a list -> int
  6679.  
  6680.     index a l returns the position of the first element of list l that is
  6681.     structurally equal to a.  The head of the list has position 0.  Raise
  6682.     Not_found if a is not present in l.
  6683.  
  6684. value assoc : 'a -> ('a * 'b) list -> 'b
  6685.  
  6686.     assoc a l returns the value associated with key a in the list of pairs l.
  6687.     That is, assoc a [ ...; (a,b); ...] = b if (a,b) is the leftmost binding
  6688.     of a in list l.  Raise Not_found if there is no value associated with a
  6689.     in the list l.
  6690.  
  6691. value assq :  'a -> ('a * 'b) list -> 'b
  6692.  
  6693.     Same as assoc, but use physical equality instead of structural equality
  6694.     to compare keys.
  6695.  
  6696. value mem_assoc : 'a -> ('a * 'b) list -> bool
  6697.  
  6698.     Same as assoc, but simply return true if a binding exists, and false if
  6699.     no bindings exist for the given key.
  6700.  
  6701.  
  6702.  
  6703. 13.13 pair:  operations on pairs
  6704.  
  6705. value fst : 'a * 'b -> 'a
  6706.  
  6707.  
  6708. Chapter 13.  The core library                                              113
  6709.  
  6710.  
  6711.     Return the first component of a pair.
  6712.  
  6713. value snd : 'a * 'b -> 'b
  6714.  
  6715.     Return the second component of a pair.
  6716.  
  6717. value split : ('a * 'b) list -> 'a list * 'b list
  6718.  
  6719.     Transform a list of pairs into a pair of lists:
  6720.     split [(a1,b1); ...; (an,bn)] is ([a1; ...; an], [b1; ...; bn])
  6721.  
  6722. value combine : 'a list * 'b list -> ('a * 'b) list
  6723.  
  6724.     Transform a pair of lists into a list of pairs:
  6725.     combine ([a1; ...; an], [b1; ...; bn]) is [(a1,b1); ...; (an,bn)].  Raise
  6726.     Invalid_argument "combine" if the two lists have different lengths.
  6727.  
  6728. value map_combine : ('a * 'b -> 'c) -> 'a list * 'b list -> 'c list
  6729.  
  6730.     map_combine f ([a1; ...; an], [b1; ...; bn]) is
  6731.     [f (a1, b1); ...; f (an, bn)].  Raise invalid_argument "map_combine" if
  6732.     the two lists have different lengths.
  6733.  
  6734. value do_list_combine : ('a * 'b -> 'c) -> 'a list * 'b list -> unit
  6735.  
  6736.     do_list_combine f ([a1; ...; an], [b1; ...; bn]) calls in turn
  6737.     f (a1, b1); ...; f (an, bn), discarding the results.  Raise
  6738.     Invalid_argument "do_list_combine" if the two lists have different
  6739.     lengths.
  6740.  
  6741.  
  6742.  
  6743. 13.14 ref:  operations on references
  6744.  
  6745. type 'a ref = ref of mutable 'a
  6746.  
  6747.     The type of references (mutable indirection cells) containing a value of
  6748.     type 'a.
  6749.  
  6750. value prefix ! : 'a ref -> 'a
  6751.  
  6752.     !r returns the current contents of reference r.  Could be defined as
  6753.     fun (ref x) -> x.
  6754.  
  6755. value prefix := : 'a ref -> 'a -> unit
  6756.  
  6757.     r := a stores the value of a in reference r.
  6758.  
  6759. value incr : int ref -> unit
  6760.  
  6761.     Increment the integer contained in the given reference.  Could be defined
  6762.     as fun r -> r := succ !r.
  6763.  
  6764. value decr : int ref -> unit
  6765.  
  6766.     Decrement the integer contained in the given reference.  Could be defined
  6767.     as fun r -> r := pred !r.
  6768.  
  6769.  
  6770. Chapter 13.   The core library                                             114
  6771.  
  6772.  
  6773. 13.15 stream:  operations on streams
  6774.  
  6775. type 'a stream
  6776.  
  6777.     The type of streams containing values of type 'a.
  6778.  
  6779. exception Parse_failure
  6780.  
  6781.     Raised by parsers when none of the first component of the stream patterns
  6782.     is accepted
  6783.  
  6784. exception Parse_error
  6785.  
  6786.     Raised by parsers when the first component of a stream pattern is
  6787.     accepted, but one of the following components is rejected
  6788.  
  6789. value stream_next : 'a stream -> 'a
  6790.  
  6791.     stream_next s returns the first element of stream s, and removes it from
  6792.     the stream.  Raise Parse_failure if the stream is empty.
  6793.  
  6794. value stream_from : (unit -> 'a) -> 'a stream
  6795.  
  6796.     stream_from f returns the stream which fetches its terminals using the
  6797.     function f.  This function could be defined as:
  6798.         let rec stream_from f = [< 'f(); stream_from f >]
  6799.     but is implemented more efficiently.
  6800.  
  6801. value stream_of_string : string -> char stream
  6802.  
  6803.     stream_of_string s returns the stream of the characters in string s.
  6804.  
  6805. value stream_of_channel : in_channel -> char stream
  6806.  
  6807.     stream_of_channel ic returns the stream of characters read on channel ic.
  6808.  
  6809. value do_stream : ('a -> 'b) -> 'a stream -> unit
  6810.  
  6811.     do_stream f s scans the whole stream s, applying the function f in turn
  6812.     to each terminal encountered
  6813.  
  6814. value stream_check : ('a -> bool) -> 'a stream -> 'a
  6815.  
  6816.     stream_check p returns the parser which returns the first terminal of the
  6817.     stream if the predicate p returns true on this terminal, and raises
  6818.     Parse_failure otherwise.
  6819.  
  6820. value end_of_stream : 'a stream -> unit
  6821.  
  6822.     Return () iff the stream is empty, and raise Parse_failure otherwise.
  6823.  
  6824. value stream_get : 'a stream -> 'a * 'a stream
  6825.  
  6826.     stream_get s return the first element of the stream s, and a stream
  6827.     containing the remaining elements of s.  Raise Parse_failure if the
  6828.     stream is empty.  The stream s is not modified.  This function makes it
  6829.     possible to access a stream non-destructively.
  6830.  
  6831.  
  6832. Chapter 13.   The core library                                             115
  6833.  
  6834.  
  6835. 13.16 string:  string operations
  6836.  
  6837. value string_length : string -> int
  6838.  
  6839.     Return the length (number of characters) of the given string.
  6840.  
  6841. value nth_char : string -> int -> char
  6842.  
  6843.     nth_char s n returns character number n in string s.  The first character
  6844.     is character number 0.  The last character is character number
  6845.     string_length s - 1.  Raise Invalid_argument "nth_char" if n is ouside
  6846.     the range 0 to (string_length s - 1).  You can also write s.[n] instead
  6847.     of nth_char s n.
  6848.  
  6849. value set_nth_char : string -> int -> char -> unit
  6850.  
  6851.     set_nth_char s n c modifies string s in place, replacing the character
  6852.     number n by c.  Raise Invalid_argument "set_nth_char" if n is ouside the
  6853.     range 0 to (string_length s - 1).  You can also write s.[n] <- c instead
  6854.     of set_nth_char s n c.
  6855.  
  6856. value prefix ^ : string -> string -> string
  6857.  
  6858.     s1 ^ s2 returns a fresh string containing the concatenation of the
  6859.     strings s1 and s2.
  6860.  
  6861. value sub_string : string -> int -> int -> string
  6862.  
  6863.     sub_string s start len returns a fresh string of length len, containing
  6864.     the characters number start to start + len - 1 of string s.  Raise
  6865.     Invalid_argument "sub_string" if start and len do not designate a valid
  6866.     substring of s; that is, if start < 0, or len < 0, or
  6867.     start + len > string_length s.
  6868.  
  6869. value create_string : int -> string
  6870.  
  6871.     create_string n returns a fresh string of length n.  The string initially
  6872.     contains arbitrary characters.
  6873.  
  6874. value make_string : int -> char -> string
  6875.  
  6876.     make_string n c returns a fresh string of length n, filled with the
  6877.     character c.
  6878.  
  6879. value fill_string : string -> int -> int -> char -> unit
  6880.  
  6881.     fill_string s start len c modifies string s in place, replacing the
  6882.     characters number start to start + len - 1 by c.  Raise
  6883.     Invalid_argument "fill_string" if start and len do not designate a valid
  6884.     substring of s.
  6885.  
  6886. value blit_string : string -> int -> string -> int -> int -> unit
  6887.  
  6888.     blit_string s1 o1 s2 o2 len copies len characters from string s1,
  6889.     starting at character number o1, to string s2, starting at character
  6890.     number o2.  It works correctly even if s1 and s2 are the same string, and
  6891.     the source and destination chunks overlap.  Raise
  6892.     Invalid_argument "blit_string" if o1 and len do not designate a valid
  6893.  
  6894.  
  6895. Chapter 13.   The core library                                             116
  6896.  
  6897.  
  6898.     substring of s1, or if o2 and len do not designate a valid substring of
  6899.     s2.
  6900.  
  6901. value replace_string : string -> string -> int -> unit
  6902.  
  6903.     replace_string dest src start copies all characters from the string src
  6904.     into the string dst, starting at character number start in dst.  Raise
  6905.     Invalid_argument "replace_string" if copying would overflow string dest.
  6906.  
  6907. value eq_string : string -> string -> bool
  6908. value neq_string : string -> string -> bool
  6909. value le_string : string -> string -> bool
  6910. value lt_string : string -> string -> bool
  6911. value ge_string : string -> string -> bool
  6912. value gt_string : string -> string -> bool
  6913.  
  6914.     Comparison functions (lexicographic ordering) between strings.
  6915.  
  6916. value compare_strings : string -> string -> int
  6917.  
  6918.     General comparison between strings.  compare_strings s1 s2 returns 0 if
  6919.     s1 and s2 are equal, or else -2 if s1 is a prefix of s2, or 2 if s2 is a
  6920.     prefix of s1, or else -1 if s1 is lexicographically before s2, or 1 if s2
  6921.     is lexicographically before s1.
  6922.  
  6923. value string_for_read : string -> string
  6924.  
  6925.     Return a copy of the argument, with special characters represented by
  6926.     escape sequences, following the lexical conventions of Caml Light.
  6927.  
  6928.  
  6929.  
  6930. 13.17 vect:  operations on vectors
  6931.  
  6932. value vect_length : 'a vect -> int
  6933.  
  6934.     Return the length (number of elements) of the given vector.
  6935.  
  6936. value vect_item : 'a vect -> int -> 'a
  6937.  
  6938.     vect_item v n returns the element number n of vector v.  The first
  6939.     element has number 0.  The last element has number vect_length v - 1.
  6940.     Raise Invalid_argument "vect_item" if n is outside the range 0 to
  6941.     (vect_length v - 1).  You can also write v.(n) instead of vect_item v n.
  6942.  
  6943. value vect_assign : 'a vect -> int -> 'a -> unit
  6944.  
  6945.     vect_assign v n x modifies vector v in place, replacing element number n
  6946.     with x.  Raise Invalid_argument "vect_assign" if n is outside the range 0
  6947.     to vect_length v - 1.  You can also write v.(n) <- x instead of
  6948.     vect_assign v n x.
  6949.  
  6950. value make_vect : int -> 'a -> 'a vect
  6951.  
  6952.     make_vect n x returns a fresh vector of length n, initialized with x.
  6953.     All the elements of this new vector are initially physically equal to x
  6954.     (see module eq).  Consequently, if x is mutable, it is shared among all
  6955.  
  6956.  
  6957. Chapter 13.   The core library                                             117
  6958.  
  6959.  
  6960.     elements of the vector, and modifying x through one of the vector entries
  6961.     will modify all other entries at the same time.
  6962.  
  6963. value make_matrix : int -> int -> 'a -> 'a vect vect
  6964.  
  6965.     make_matrix dimx dimy e returns a two-dimensional array (a vector of
  6966.     vectors) with first dimension dimx and second dimension dimy.  All the
  6967.     elements of this new matrix are initially physically equal to e.  The
  6968.     element (x,y) of a matrix m is accessed with the notation m.(x).(y).
  6969.  
  6970. value concat_vect : 'a vect -> 'a vect -> 'a vect
  6971.  
  6972.     concat_vect v1 v2 returns a fresh vector containing the concatenation of
  6973.     vectors v1 and v2.
  6974.  
  6975. value sub_vect : 'a vect -> int -> int -> 'a vect
  6976.  
  6977.     sub_vect v start len returns a fresh vector of length len, containing the
  6978.     elements number start to start + len - 1 of vector v.  Raise
  6979.     Invalid_argument "sub_vect" if start and len do not designate a valid
  6980.     subvector of v; that is, if start < 0, or len < 0, or
  6981.     start + len > vect_length v.
  6982.  
  6983. value copy_vect : 'a vect -> 'a vect
  6984.  
  6985.     copy_vect v returns a copy of v, that is, a fresh vector containing the
  6986.     same elements as v.
  6987.  
  6988. value fill_vect : 'a vect -> int -> int -> 'a -> unit
  6989.  
  6990.     fill_vect v ofs len x modifies the vector v in place, storing x in
  6991.     elements number ofs to ofs + len - 1.  Raise Invalid_argument "fill_vect"
  6992.     if ofs and len do not designate a valid subvector of v.
  6993.  
  6994. value blit_vect : 'a vect -> int -> 'a vect -> int -> int -> unit
  6995.  
  6996.     blit_vect v1 o1 v2 o2 len copies len elements from vector v1, starting at
  6997.     element number o1, to vector v2, starting at element number o2.  It works
  6998.     correctly even if v1 and v2 are the same vector, and the source and
  6999.     destination chunks overlap.  Raise Invalid_argument "blit_vect" if o1 and
  7000.     len do not designate a valid subvector of v1, or if o2 and len do not
  7001.     designate a valid subvector of v2.
  7002.  
  7003. value list_of_vect : 'a vect -> 'a list
  7004.  
  7005.     list_of_vect v returns the list of all the elements of v, that is:
  7006.     [v.(0); v.(1); ...; v.(vect_length v - 1)].
  7007.  
  7008. value vect_of_list : 'a list -> 'a vect
  7009.  
  7010.     vect_of_list l returns a fresh vector containing the elements of l.
  7011.  
  7012. value map_vect : ('a -> 'b) -> 'a vect -> 'b vect
  7013.  
  7014.     map_vect f v applies function f to all the elements of v, and builds a
  7015.     vector with the results returned by f:
  7016.     [| f v.(0); f v.(1); ...; f v.(vect_length v - 1) |].
  7017.  
  7018.  
  7019. Chapter 13.   The core library                                             118
  7020.  
  7021.  
  7022. value map_vect_list : ('a -> 'b) -> 'a vect -> 'b list
  7023.  
  7024.     map_vect_list f v applies function f to all the elements of v, and builds
  7025.     a list with the results returned by f:
  7026.     [ f v.(0); f v.(1); ...; f v.(vect_length v - 1) ].
  7027.  
  7028. value do_vect : ('a -> 'b) -> 'a vect -> unit
  7029.  
  7030.     do_vect f v applies function f in turn to all the elements of v,
  7031.     discarding all the results:
  7032.     f v.(0); f v.(1); ...; f v.(vect_length v - 1); ().
  7033.  
  7034.  
  7035.  
  7036.  
  7037.  
  7038.  
  7039.  
  7040.  
  7041.  
  7042.  
  7043.  
  7044. Chapter 14
  7045.  
  7046.  
  7047.  
  7048. The standard library
  7049.  
  7050.  
  7051.  
  7052. This chapter describes the functions provided by the Caml Light standard
  7053. library.  Just as the modules from the core library, the modules from the
  7054. standard library are automatically linked with the user's object code files by
  7055. the camlc command.  Hence, the globals defined by these libraries can be used
  7056. in standalone programs without having to add any .zo file on the command line
  7057. for the linking phase.  Similarly, in interactive use, these globals can be
  7058. used in toplevel phrases without having to load any .zo file in memory.
  7059.   Unlike the modules from the core library, the modules from the standard
  7060. library are not automatically ``opened'' when a compilation starts, or when
  7061. the toplevel system is launched.  Hence it is necessary to use qualified
  7062. identifiers to refer to the functions provided by these modules, or to add
  7063. #open directives.
  7064.  
  7065.  
  7066. Conventions
  7067.  
  7068. For easy reference, the modules are listed below in alphabetical order of
  7069. module names.  For each module, the declarations from its interface file are
  7070. printed one by one in typewriter font, followed by a short comment.  All
  7071. modules and the identifiers they export are indexed at the end of this report.
  7072.  
  7073.  
  7074. 14.1 arg:  parsing of command line arguments
  7075.  
  7076.     This module provides a general mechanism for extracting options and
  7077.     arguments from the command line to the program.
  7078.  
  7079.  
  7080.     Syntax of command lines:  A keyword is a character string starting with a
  7081.     -.  An option is a keyword alone or followed by an argument.  There are
  7082.     four types of keywords:  Unit, String, Int, and Float.  Unit keywords do
  7083.     not take an argument.  String, Int, and Float keywords take the following
  7084.     word on the command line as an argument.  Arguments not preceded by a
  7085.     keyword are called anonymous arguments.
  7086.  
  7087.  
  7088.     Examples (cmd is assumed to be the command name):
  7089.     cmd -flag           (a unit option)
  7090.     cmd -int 1          (an int option with argument 1)
  7091.     cmd -string foobar  (a string option with argument "foobar")
  7092.     cmd -float 12.34    (a float option with argument 12.34)
  7093.     cmd 1 2 3           (three anonymous arguments:  "1", "2", and "3")
  7094.     cmd 1 2 -flag 3 -string bar 4
  7095.                         (four anonymous arguments, a unit option, and
  7096.  
  7097.  
  7098.                                      119
  7099.  
  7100.  
  7101. Chapter 14.   The standard library                                         120
  7102.  
  7103.  
  7104.                          a string option with argument "bar")
  7105.  
  7106. type spec =
  7107.   String of (string -> unit)
  7108. | Int of (int -> unit)
  7109. | Unit of (unit -> unit)
  7110. | Float of (float -> unit)
  7111.  
  7112.     The concrete type describing the behavior associated with a keyword.
  7113.  
  7114. value parse : (string * spec) list -> (string -> unit) -> unit
  7115.  
  7116.     parse speclist anonfun parses the command line, calling the functions in
  7117.     speclist whenever appropriate, and anonfun on anonymous arguments.  The
  7118.     functions are called in the same order as they appear on the command
  7119.     line.  The strings in the (string * spec) list are keywords and must
  7120.     start with a -, else they are ignored.  For the user to be able to
  7121.     specify anonymous arguments starting with a -, include for example
  7122.     ("--", String anonfun) in speclist.
  7123.  
  7124. exception Bad of string
  7125.  
  7126.     Functions in speclist or anonfun can raise Bad with an error message to
  7127.     reject invalid arguments.
  7128.  
  7129.  
  7130.  
  7131. 14.2 baltree:  basic balanced binary trees
  7132.  
  7133.     This module implements balanced ordered binary trees.  All operations
  7134.     over binary trees are applicative (no side-effects).  The set and map
  7135.     modules are based on this module.  This modules gives a more direct
  7136.     access to the internals of the binary tree implementation than the set
  7137.     and map abstractions, but is more delicate to use and not as safe.  For
  7138.     advanced users only.
  7139.  
  7140. type 'a t = Empty | Node of 'a t * 'a * 'a t * int
  7141.  
  7142.     The type of trees containing elements of type 'a.  Empty is the empty
  7143.     tree (containing no elements).
  7144.  
  7145. type 'a contents = Nothing | Something of 'a
  7146.  
  7147.     Used with the functions modify and split, to represent the presence or
  7148.     the absence of an element in a tree.
  7149.  
  7150. value add: ('a -> int) -> 'a -> 'a t -> 'a t
  7151.  
  7152.     add f x t inserts the element x into the tree t.  f is an ordering
  7153.     function:  f y must return 0 if x and y are equal (or equivalent), a
  7154.     negative integer if x is smaller than y, and a positive integer if x is
  7155.     greater than y.  The tree t is returned unchanged if it already contains
  7156.     an element equivalent to x (that is, an element y such that f y is 0).
  7157.     The ordering f must be consistent with the orderings used to build t with
  7158.     add, remove, modify or split operations.
  7159.  
  7160. value contains: ('a -> int) -> 'a t -> bool
  7161.  
  7162.  
  7163. Chapter 14.   The standard library                                         121
  7164.  
  7165.  
  7166.     contains f t checks whether t contains an element satisfying f, that is,
  7167.     an element x such that f x is 0.  f is an ordering function with the same
  7168.     constraints as for add.  It can be coarser (identify more elements) than
  7169.     the orderings used to build t, but must be consistent with them.
  7170.  
  7171. value find: ('a -> int) -> 'a t -> 'a
  7172.  
  7173.     Same as contains, except that find f t returns the element x such that
  7174.     f x is 0, or raises Not_found if none has been found.
  7175.  
  7176. value remove: ('a -> int) -> 'a t -> 'a t
  7177.  
  7178.     remove f t removes one element x of t such that f x is 0.  f is an
  7179.     ordering function with the same constraints as for add.  t is returned
  7180.     unchanged if it does not contain any element satisfying f.  If several
  7181.     elements of t satisfy f, only one is removed.
  7182.  
  7183. value modify: ('a -> int) -> ('a contents -> 'a contents) -> 'a t -> 'a t
  7184.  
  7185.     General insertion/modification/deletion function.  modify f g t searchs t
  7186.     for an element x satisfying the ordering function f.  If one is found, g
  7187.     is applied to Something x; if g returns Nothing, the element x is
  7188.     removed; if g returns Something y, the element y replaces x in the tree.
  7189.     (It is assumed that x and y are equivalent, in particular, that f y is
  7190.     0.)  If the tree does not contain any x satisfying f, g is applied to
  7191.     Nothing; if it returns Nothing, the tree is returned unchanged; if it
  7192.     returns Something x, the element x is inserted in the tree.  (It is
  7193.     assumed that f x is 0.)  The functions add and remove are special cases
  7194.     of modify, slightly more efficient.
  7195.  
  7196. value split: ('a -> int) -> 'a t -> 'a t * 'a contents * 'a t
  7197.  
  7198.     split f t returns a triple (less, elt, greater) where less is a tree
  7199.     containing all elements x of t such that f x is negative, greater is a
  7200.     tree containing all elements x of t such that f x is positive, and elt is
  7201.     Something x if t contains an element x such that f x is 0, and Nothing
  7202.     otherwise.
  7203.  
  7204. value compare: ('a -> 'a -> int) -> 'a t -> 'a t -> int
  7205.  
  7206.     Compare two trees.  The first argument f is a comparison function over
  7207.     the tree elements:  f e1 e2 is zero if the elements e1 and e2 are equal,
  7208.     negative if e1 is smaller than e2, and positive if e1 is greater than e2.
  7209.     compare f t1 t2 compares the fringes of t1 and t2 by lexicographic
  7210.     extension of f.
  7211.  
  7212.  
  7213.  
  7214. 14.3 filename:  operations on file names
  7215.  
  7216. value current_dir_name : string
  7217.  
  7218.     The conventional name for the current directory (e.g.  . in Unix).
  7219.  
  7220. value concat : string -> string -> string
  7221.  
  7222.     concat dir file returns a file name that designates file file in
  7223.     directory dir.
  7224.  
  7225.  
  7226. Chapter 14.   The standard library                                         122
  7227.  
  7228.  
  7229. value is_absolute : string -> bool
  7230.  
  7231.     Return true if the file name is absolute or starts with an explicit
  7232.     reference to the current directory (./ or ../ in Unix), and false if it
  7233.     is relative to the current directory.
  7234.  
  7235. value check_suffix : string -> string -> bool
  7236.  
  7237.     check_suffix name suff returns true if the filename name ends with the
  7238.     suffix suff.
  7239.  
  7240. value chop_suffix : string -> string -> string
  7241.  
  7242.     chop_suffix name suff removes the suffix suff from the filename name.
  7243.     The behavior is undefined if name does not end with the suffix suff.
  7244.  
  7245. value basename : string -> string
  7246. value dirname : string -> string
  7247.  
  7248.     Split a file name into directory name / base file name.
  7249.     concat (dirname name) (basename name) returns a file name which is
  7250.     equivalent to name.  Moreover, after setting the current directory to
  7251.     dirname name (with sys__chdir), references to basename name (which is a
  7252.     relative file name) designate the same file as name before the call to
  7253.     chdir.
  7254.  
  7255.  
  7256.  
  7257. 14.4 format:  pretty printing
  7258.  
  7259.     This module implements a pretty-printing facility to format text within
  7260.     ``pretty-printing boxes''.  The pretty-printer breaks lines at specified
  7261.     break hints, and indents lines according to the box structure.
  7262.  
  7263.  
  7264.     The behaviour of pretty-printing commands is unspecified if there is no
  7265.     opened pretty-printing box.  Each box opened via one of the open_
  7266.     functions below must be closed using close_box for proper formatting.
  7267.     Otherwise, some of the material printed in the boxes may not be output,
  7268.     or may be formatted incorrectly.
  7269.  
  7270.  
  7271.     In case of interactive use, the system closes all opened boxes and
  7272.     flushes all pending text (as with the print_newline function) after each
  7273.     phrase.  Each phrase is therefore executed in the initial state of the
  7274.     pretty-printer.
  7275.  
  7276.  
  7277. Boxes
  7278.  
  7279. value open_vbox : int -> unit
  7280.  
  7281.     open_vbox d opens a new pretty-printing box with offset d.  This box is
  7282.     ``vertical'':  every break hint inside this box leads to a new line.
  7283.     When a new line is printed in the box, d is added to the current
  7284.     indentation.
  7285.  
  7286. value open_hbox : unit -> unit
  7287.  
  7288.  
  7289. Chapter 14.   The standard library                                         123
  7290.  
  7291.  
  7292.     open_hbox () opens a new pretty-printing box.  This box is
  7293.     ``horizontal'':  the line is not split in this box (new lines may still
  7294.     occur inside boxes nested deeper).
  7295.  
  7296. value open_hvbox : int -> unit
  7297.  
  7298.     open_hovbox d opens a new pretty-printing box with offset d.  This box is
  7299.     ``horizontal-vertical'':  it behaves as an ``horizontal'' box if it fits
  7300.     on a single line, otherwise it behaves as a ``vertical'' box.  When a new
  7301.     line is printed in the box, d is added to the current indentation.
  7302.  
  7303. value open_hovbox : int -> unit
  7304.  
  7305.     open_hovbox d opens a new pretty-printing box with offset d.  This box is
  7306.     ``horizontal or vertical'':  break hints inside this box may lead to a
  7307.     new line, if there is no more room on the line to print the remainder of
  7308.     the box.  When a new line is printed in the box, d is added to the
  7309.     current indentation.
  7310.  
  7311. value close_box : unit -> unit
  7312.  
  7313.     Close the most recently opened pretty-printing box.
  7314.  
  7315.  
  7316. Formatting functions
  7317.  
  7318. value print_string : string -> unit
  7319.  
  7320.     print_string str prints str in the current box.
  7321.  
  7322. value print_as : int -> string -> unit
  7323.  
  7324.     print_as len str prints str in the current box.  The pretty-printer
  7325.     formats str as if it were of length len.
  7326.  
  7327. value print_int : int -> unit
  7328.  
  7329.     Print an integer in the current box.
  7330.  
  7331. value print_float : float -> unit
  7332.  
  7333.     Print a floating point number in the current box.
  7334.  
  7335. value print_char : char -> unit
  7336.  
  7337.     Print a character in the current box.
  7338.  
  7339. value print_bool : bool -> unit
  7340.  
  7341.     Print an boolean in the current box.
  7342.  
  7343.  
  7344. Break hints
  7345.  
  7346. value print_break : int * int -> unit
  7347.  
  7348.  
  7349. Chapter 14.   The standard library                                         124
  7350.  
  7351.  
  7352.     Insert a break hint in a pretty-printing box.
  7353.     print_break (nspaces, offset) indicates that the line may be split (a
  7354.     newline character is printed) at this point, if the contents of the
  7355.     current box does not fit on one line.  If the line is split at that
  7356.     point, offset is added to the current indentation.  If the line is not
  7357.     split, nspaces spaces are printed.
  7358.  
  7359. value print_cut : unit -> unit
  7360.  
  7361.     print_cut () is equivalent to print_break (0,0).  This allows line
  7362.     splitting at the current point, without printing spaces or adding
  7363.     indentation.
  7364.  
  7365. value print_space : unit -> unit
  7366.  
  7367.     print_space () is equivalent to print_break (1,0).  This either prints
  7368.     one space or splits the line at that point.
  7369.  
  7370. value force_newline : unit -> unit
  7371.  
  7372.     Force a newline in the current box.
  7373.  
  7374. value print_flush : unit -> unit
  7375.  
  7376.     Flush the pretty printer:  all opened boxes are closed, and all pending
  7377.     text is displayed.
  7378.  
  7379. value print_newline : unit -> unit
  7380.  
  7381.     Equivalent to print_flush followed by a new line.
  7382.  
  7383. value print_if_newline : unit -> unit
  7384.  
  7385.     If the preceding line has not been split, the next formatting command is
  7386.     ignored.
  7387.  
  7388.  
  7389. Tabulations
  7390.  
  7391. value open_tbox : unit -> unit
  7392.  
  7393.     Open a tabulation box.
  7394.  
  7395. value close_tbox : unit -> unit
  7396.  
  7397.     Close the most recently opened tabulation box.
  7398.  
  7399. value print_tbreak : int * int -> unit
  7400.  
  7401.     Break hint in a tabulation box.  print_tbreak (spaces, offset) moves the
  7402.     insertion point to the next tabulation (spaces being added to this
  7403.     position).  Nothing occurs if insertion point is already on a tabulation
  7404.     mark.  If there is no next tabulation on the line, then a newline is
  7405.     printed and the insertion point moves to the first tabulation of the box.
  7406.     If a new line is printed, offset is added to the current indentation.
  7407.  
  7408.  
  7409. Chapter 14.  The standard library                                          125
  7410.  
  7411.  
  7412. value set_tab : unit -> unit
  7413.  
  7414.     Set a tabulation mark at the current insertion point.
  7415.  
  7416. value print_tab : unit -> unit
  7417.  
  7418.     print_tab () is equivalent to print_tbreak (0,0).
  7419.  
  7420.  
  7421. Margin
  7422.  
  7423. value set_margin : int -> unit
  7424.  
  7425.     set_margin d sets the value of the right margin to d (in characters):
  7426.     this value is used to detect line overflows that leads to split lines.
  7427.     Nothing happens if d is not greater than 1.
  7428.  
  7429. value get_margin : unit -> int
  7430.  
  7431.     Return the position of the right margin.
  7432.  
  7433.  
  7434. Maximum indentation limit
  7435.  
  7436. value set_max_indent : int -> unit
  7437.  
  7438.     set_max_indent d sets the value of the maximum indentation limit to d (in
  7439.     characters):  once this limit is reached, boxes are rejected to the left,
  7440.     if they do not fit on the current line.  Nothing happens if d is not
  7441.     greater than 1.
  7442.  
  7443. value get_max_indent : unit -> int
  7444.  
  7445.     Return the value of the maximum indentation limit (in characters).
  7446.  
  7447.  
  7448. Formatting depth:  maximum number of boxes allowed before ellipsis
  7449.  
  7450. value set_max_boxes : int -> unit
  7451.  
  7452.     set_max_boxes max sets the maximum number of boxes simultaneously opened.
  7453.     Material inside boxes nested deeper is printed as an ellipsis (more
  7454.     precisely as the text returned by get_ellipsis_text).  Nothing happens if
  7455.     max is not greater than 1.
  7456.  
  7457. value get_max_boxes : unit -> int
  7458.  
  7459.     Return the maximum number of boxes allowed before ellipsis.
  7460.  
  7461.  
  7462. Ellipsis
  7463.  
  7464. value set_ellipsis_text : string -> unit
  7465.  
  7466.     Set the text of the ellipsis printed when too many boxes are opened (a
  7467.     single dot, ., by default).
  7468.  
  7469.  
  7470. Chapter 14.  The standard library                                          126
  7471.  
  7472.  
  7473. value get_ellipsis_text : unit -> string
  7474.  
  7475.     Return the text of the ellipsis.
  7476.  
  7477.  
  7478. Redirecting formatter output
  7479.  
  7480. value set_formatter_output_channel : out_channel -> unit
  7481.  
  7482.     Redirect the pretty-printer output to the given channel.
  7483.  
  7484. value set_formatter_output_functions :
  7485.         (string -> int -> int -> unit) -> (unit -> unit) -> unit
  7486.  
  7487.     set_formatter_output_functions out flush redirects the pretty-printer
  7488.     output to the functions out and flush.  The out function performs the
  7489.     pretty-printer output.  It is called with a string s, a start position p,
  7490.     and a number of characters n; it is supposed to output characters p to
  7491.     p+n-1 of s.  The flush function is called whenever the pretty-printer is
  7492.     flushed using print_flush or print_newline.
  7493.  
  7494. value get_formatter_output_functions :
  7495.         unit -> (string -> int -> int -> unit) * (unit -> unit)
  7496.  
  7497.     Return the current output functions of the pretty-printer.
  7498.  
  7499.  
  7500.  
  7501. 14.5 gc:  memory management control and statistics
  7502.  
  7503. type stat = {
  7504.   minor_words : int;
  7505.   promoted_words : int;
  7506.   major_words : int;
  7507.   minor_collections : int;
  7508.   major_collections : int;
  7509.   heap_words : int;
  7510.   heap_chunks : int;
  7511.   live_words : int;
  7512.   live_blocks : int;
  7513.   free_words : int;
  7514.   free_blocks : int;
  7515.   largest_words : int;
  7516.   fragments : int
  7517. }
  7518.  
  7519.     The memory management counters are returned in a stat record.  All the
  7520.     numbers are computed since the start of the program.  The fields of this
  7521.     record are:
  7522.     minor_words Number of words allocated in the minor heap.
  7523.     promoted_words Number of words allocated in the minor heap that survived
  7524.     a minor collection and were moved to the major heap.
  7525.     major_words Number of words allocated in the major heap, including the
  7526.     promoted words.
  7527.     minor_collections Number of minor collections.
  7528.     major_collections Number of major collection cycles, not counting the
  7529.     current cycle.
  7530.     heap_words Total size of the major heap, in words.
  7531.  
  7532.  
  7533. Chapter 14.   The standard library                                         127
  7534.  
  7535.  
  7536.     heap_chunks Number of times the major heap size was increased.
  7537.     live_words Number of words of live data in the major heap, including the
  7538.     header words.
  7539.     live_blocks Number of live objects in the major heap.
  7540.     free_words Number of words in the free list.
  7541.     free_blocks Number of objects in the free list.
  7542.     largest_words Size (in words) of the largest object in the free list.
  7543.     fragments Number of wasted words due to fragmentation.  These are 1-words
  7544.     free blocks placed between two live objects.  They cannot be inserted in
  7545.     the free list, thus they are not available for allocation.
  7546.     The total amount of memory allocated by the program is (in words)
  7547.     minor_words + major_words - promoted_words.  Multiply by the word size (4
  7548.     on a 32-bit machine, 8 on a 64-bit machine) to get the number of bytes.
  7549.  
  7550. type control = {
  7551.   mutable minor_heap_size : int;
  7552.   mutable major_heap_increment : int;
  7553.   mutable space_overhead : int;
  7554.   mutable verbose : bool
  7555. }
  7556.  
  7557.     The GC parameters are given as a control record.  The fields are:
  7558.     minor_heap_size The size (in words) of the minor heap.  Changing this
  7559.     parameter will trigger a minor collection.
  7560.     major_heap_increment The minimum number of words to add to the major heap
  7561.     when increasing it.
  7562.     space_overhead The major GC speed is computed from this parameter.  This
  7563.     is the percentage of heap space that will be "wasted" because the GC does
  7564.     not immediatly collect unreachable objects.  The GC will work more (use
  7565.     more CPU time and collect objects more eagerly) if space_overhead is
  7566.     smaller.  The computation of the GC speed assumes that the amount of live
  7567.     data is constant.
  7568.     verbose This flag controls the GC messages on standard error output.
  7569.  
  7570. value stat : unit -> stat
  7571.  
  7572.     Return the current values of the memory management counters in a stat
  7573.     record.
  7574.  
  7575. value print_stat : io__out_channel -> unit
  7576.  
  7577.     Print the current values of the memory management counters (in
  7578.     human-readable form) into the channel argument.
  7579.  
  7580. value get : unit -> control
  7581.  
  7582.     Return the current values of the GC parameters in a control record.
  7583.  
  7584. value set : control -> unit
  7585.  
  7586.     set r changes the GC parameters according to the control record r.  The
  7587.     normal usage is:
  7588.  
  7589.  
  7590.            let r = gc__get () in    (* Get the current parameters. *)
  7591.              r.verbose <- true;     (* Change some of them. *)
  7592.              gc__set r              (* Set the new values. *)
  7593.  
  7594.  
  7595. Chapter 14.  The standard library                                          128
  7596.  
  7597.  
  7598. value minor : unit -> unit
  7599.  
  7600.     Trigger a minor collection.
  7601.  
  7602. value major : unit -> unit
  7603.  
  7604.     Finish the current major collection cycle.
  7605.  
  7606. value full_major : unit -> unit
  7607.  
  7608.     Finish the current major collection cycle and perform a complete new
  7609.     cycle.  This will collect all currently unreachable objects.
  7610.  
  7611.  
  7612.  
  7613. 14.6 genlex:  a generic lexical analyzer
  7614.  
  7615.     This module implements a simple ``standard'' lexical analyzer, presented
  7616.     as a function from character streams to token streams.  It implements
  7617.     roughly the lexical conventions of Caml, but is parameterized by the set
  7618.     of keywords of your language.
  7619.  
  7620. type token =
  7621.     Kwd of string
  7622.   | Ident of string
  7623.   | Int of int
  7624.   | Float of float
  7625.   | String of string
  7626.   | Char of char
  7627.  
  7628.     The type of tokens.  The lexical classes are:  Int and Float for integer
  7629.     and floating-point numbers; String for string literals, enclosed in
  7630.     double quotes; Char for character literals, enclosed in backquotes; Ident
  7631.     for identifiers (either sequences of letters, digits, underscores and
  7632.     quotes, or sequences of ``operator characters'' such as +, *, etc); and
  7633.     Kwd for keywords (either identifiers or single ``special characters''
  7634.     such as (, }, etc).
  7635.  
  7636. value make_lexer: string list -> (char stream -> token stream)
  7637.  
  7638.     Construct the lexer function.  The first argument is the list of
  7639.     keywords.  An identifier s is returned as Kwd s if s belongs to this
  7640.     list, and as Ident s otherwise.  A special character s is returned as
  7641.     Kwd s if s belongs to this list, and cause a lexical error (exception
  7642.     Parse_error) otherwise.  Blanks and newlines are skipped.  Comments
  7643.     delimited by (* and *) are skipped as well, and can be nested.
  7644.  
  7645.  
  7646.     Example:  a lexer suitable for a desk calculator is obtained by
  7647.  
  7648.  
  7649.                let lexer = make_lexer ["+";"-";"*";"/";"let";"="; "("; ")"]
  7650.  
  7651.  
  7652.     The associated parser would be a function from token stream to, for
  7653.     instance, int, and would have rules such as:
  7654.  
  7655.  
  7656. Chapter 14.   The standard library                                         129
  7657.  
  7658.  
  7659.                let parse_expr = function
  7660.                       [< 'Int n >] -> n
  7661.                     | [< 'Kwd "("; parse_expr n; 'Kwd ")" >] -> n
  7662.                     | [< parse_expr n1; (parse_remainder n1) n2 >] -> n2
  7663.                and parse_remainder n1 = function
  7664.                       [< 'Kwd "+"; parse_expr n2 >] -> n1+n2
  7665.                     | ...
  7666.  
  7667.  
  7668.  
  7669.  
  7670. 14.7 hashtbl:  hash tables and hash functions
  7671.  
  7672.     Hash tables are hashed association tables, with in-place modification.
  7673.  
  7674. type ('a, 'b) t
  7675.  
  7676.     The type of hash tables from type 'a to type 'b.
  7677.  
  7678. value new : int -> ('a,'b) t
  7679.  
  7680.     new n creates a new, empty hash table, with initial size n.  The table
  7681.     grows as needed, so n is just an initial guess.  Better results are said
  7682.     to be achieved when n is a prime number.
  7683.  
  7684. value clear : ('a, 'b) t -> unit
  7685.  
  7686.     Empty a hash table.
  7687.  
  7688. value add : ('a, 'b) t -> 'a -> 'b -> unit
  7689.  
  7690.     add tbl x y adds a binding of x to y in table tbl.  Previous bindings for
  7691.     x are not removed, but simply hidden.  That is, after performing
  7692.     remove tbl x, the previous binding for x, if any, is restored.  (This is
  7693.     the semantics of association lists.)
  7694.  
  7695. value find : ('a, 'b) t -> 'a -> 'b
  7696.  
  7697.     find tbl x returns the current binding of x in tbl, or raises Not_found
  7698.     if no such binding exists.
  7699.  
  7700. value find_all : ('a, 'b) t -> 'a -> 'b list
  7701.  
  7702.     find_all tbl x returns the list of all data associated with x in tbl.
  7703.     The current binding is returned first, then the previous bindings, in
  7704.     reverse order of introduction in the table.
  7705.  
  7706. value remove : ('a, 'b) t -> 'a -> unit
  7707.  
  7708.     remove tbl x removes the current binding of x in tbl, restoring the
  7709.     previous binding if it exists.  It does nothing if x is not bound in tbl.
  7710.  
  7711. value do_table : ('a -> 'b -> 'c) -> ('a, 'b) t -> unit
  7712.  
  7713.     do_table f tbl applies f to all bindings in table tbl, discarding all the
  7714.     results.  f receives the key as first argument, and the associated value
  7715.     as second argument.  Each binding is presented exactly once to f.  The
  7716.     order in which the bindings are passed to f is unpredictable, except that
  7717.  
  7718.  
  7719. Chapter 14.   The standard library                                         130
  7720.  
  7721.  
  7722.     successive bindings for the same key are presented in reverse
  7723.     chronological order (most recent first).
  7724.  
  7725. value do_table_rev : ('a -> 'b -> 'c) -> ('a, 'b) t -> unit
  7726.  
  7727.     Same as do_table, except that successive bindings for the same key are
  7728.     presented in chronological order (oldest first).
  7729.  
  7730.  
  7731. The polymorphic hash primitive
  7732.  
  7733. value hash : 'a -> int
  7734.  
  7735.     hash x associates a positive integer to any value of any type.  It is
  7736.     guaranteed that if x = y, then hash x = hash y.  Moreover, hash always
  7737.     terminates, even on cyclic structures.
  7738.  
  7739. value hash_param : int -> int -> 'a -> int
  7740.  
  7741.     hash_param n m x computes a hash value for x, with the same properties as
  7742.     for hash.  The two extra parameters n and m give more precise control
  7743.     over hashing.  Hashing performs a depth-first, right-to-left traversal of
  7744.     the structure x, stopping after n meaningful nodes were encountered, or m
  7745.     nodes, meaningful or not, were encountered.  Meaningful nodes are:
  7746.     integers; floating-point numbers; strings; characters; booleans; and
  7747.     constant constructors.  Larger values of m and n means that more nodes
  7748.     are taken into account to compute the final hash value, and therefore
  7749.     collisions are less likely to happen.  However, hashing takes longer.
  7750.     The parameters m and n govern the tradeoff between accuracy and speed.
  7751.  
  7752.  
  7753.  
  7754. 14.8 lexing:  the run-time library for lexers generated by camllex
  7755.  
  7756. Lexer buffers
  7757.  
  7758. type lexbuf =
  7759.   { refill_buff : lexbuf -> unit;
  7760.     lex_buffer : string;
  7761.     mutable lex_abs_pos : int;
  7762.     mutable lex_start_pos : int;
  7763.     mutable lex_curr_pos : int;
  7764.     mutable lex_last_pos : int;
  7765.     mutable lex_last_action : lexbuf -> obj }
  7766.  
  7767.     The type of lexer buffers.  A lexer buffer is the argument passed to the
  7768.     scanning functions defined by the generated scanners.  The lexer buffer
  7769.     holds the current state of the scanner, plus a function to refill the
  7770.     buffer from the input.
  7771.  
  7772. value create_lexer_channel : in_channel -> lexbuf
  7773.  
  7774.     Create a lexer buffer on the given input channel.
  7775.     create_lexer_channel inchan returns a lexer buffer which reads from the
  7776.     input channel inchan, at the current reading position.
  7777.  
  7778. value create_lexer_string : string -> lexbuf
  7779.  
  7780.  
  7781. Chapter 14.   The standard library                                         131
  7782.  
  7783.  
  7784.     Create a lexer buffer which reads from the given string.  Reading starts
  7785.     from the first character in the string.  An end-of-input condition is
  7786.     generated when the end of the string is reached.
  7787.  
  7788. value create_lexer : (string -> int -> int) -> lexbuf
  7789.  
  7790.     Create a lexer buffer with the given function as its reading method.
  7791.     When the scanner needs more characters, it will call the given function,
  7792.     giving it a character string s and a character count n.  The function
  7793.     should put n characters or less in s, starting at character number 0, and
  7794.     return the number of characters provided.  A return value of 0 means end
  7795.     of input.
  7796.  
  7797.  
  7798. Functions for lexer semantic actions
  7799.  
  7800.     The following functions can be called from the semantic actions of lexer
  7801.     definitions (the ML code enclosed in braces that computes the value
  7802.     returned by lexing functions).  They give access to the character string
  7803.     matched by the regular expression associated with the semantic action.
  7804.     These functions must be applied to the argument lexbuf, which, in the
  7805.     code generated by camllex, is bound to the lexer buffer passed to the
  7806.     parsing function.
  7807.  
  7808. value get_lexeme : lexbuf -> string
  7809.  
  7810.     get_lexeme lexbuf returns the string matched by the regular expression.
  7811.  
  7812. value get_lexeme_char : lexbuf -> int -> char
  7813.  
  7814.     get_lexeme_char lexbuf i returns character number i in the matched
  7815.     string.
  7816.  
  7817. value get_lexeme_start : lexbuf -> int
  7818.  
  7819.     get_lexeme_start lexbuf returns the position in the input stream of the
  7820.     first character of the matched string.  The first character of the stream
  7821.     has position 0.
  7822.  
  7823. value get_lexeme_end : lexbuf -> int
  7824.  
  7825.     get_lexeme_end lexbuf returns the position in the input stream of the
  7826.     character following the last character of the matched string.  The first
  7827.     character of the stream has position 0.
  7828.  
  7829.  
  7830.  
  7831. 14.9 map:  association tables over ordered types
  7832.  
  7833.     This module implements applicative association tables, also known as
  7834.     finite maps or dictionaries, given a total ordering function over the
  7835.     keys.  All operations over maps are purely applicative (no side-effects).
  7836.     The implementation uses balanced binary trees, and therefore searching
  7837.     and insertion take time logarithmic in the size of the map.
  7838.  
  7839. type ('a, 'b) t
  7840.  
  7841.     The type of maps from type 'a to type 'b.
  7842.  
  7843.  
  7844. Chapter 14.   The standard library                                         132
  7845.  
  7846.  
  7847. value empty: ('a -> 'a -> int) -> ('a, 'b) t
  7848.  
  7849.     The empty map.  The argument is a total ordering function over the set
  7850.     elements.  This is a two-argument function f such that f e1 e2 is zero if
  7851.     the elements e1 and e2 are equal, f e1 e2 is strictly negative if e1 is
  7852.     smaller than e2, and f e1 e2 is strictly positive if e1 is greater than
  7853.     e2.  Examples:  a suitable ordering function for type int is prefix -.
  7854.     You can also use the generic structural comparison function eq__compare.
  7855.  
  7856. value add: 'a -> 'b -> ('a, 'b) t -> ('a, 'b) t
  7857.  
  7858.     add x y m returns a map containing the same bindings as m, plus a binding
  7859.     of x to y.  Previous bindings for x in m are not removed, but simply
  7860.     hidden:  they reappear after performing a remove operation.  (This is the
  7861.     semantics of association lists.)
  7862.  
  7863. value find:'a -> ('a, 'b) t -> 'b
  7864.  
  7865.     find x m returns the current binding of x in m, or raises Not_found if no
  7866.     such binding exists.
  7867.  
  7868. value remove: 'a -> ('a, 'b) t -> ('a, 'b) t
  7869.  
  7870.     remove x m returns a map containing the same bindings as m except the
  7871.     current binding for x.  The previous binding for x is restored if it
  7872.     exists.  m is returned unchanged if x is not bound in m.
  7873.  
  7874. value iter: ('a -> 'b -> 'c) -> ('a, 'b) t -> unit
  7875.  
  7876.     iter f m applies f to all bindings in map m, discarding the results.  f
  7877.     receives the key as first argument, and the associated value as second
  7878.     argument.  The order in which the bindings are passed to f is
  7879.     unspecified.  Only current bindings are presented to f:  bindings hidden
  7880.     by more recent bindings are not passed to f.
  7881.  
  7882.  
  7883.  
  7884. 14.10 parsing:  the run-time library for parsers generated by camlyacc
  7885.  
  7886. value symbol_start : unit -> int
  7887. value symbol_end : unit -> int
  7888.  
  7889.     symbol_start and symbol_end are to be called in the action part of a
  7890.     grammar rule only.  They return the position of the string that matches
  7891.     the left-hand side of the rule:  symbol_start() returns the position of
  7892.     the first character; symbol_end() returns the position of the last
  7893.     character, plus one.  The first character in a file is at position 0.
  7894.  
  7895. value rhs_start: int -> int
  7896. value rhs_end: int -> int
  7897.  
  7898.     Same as symbol_start and symbol_end above, but return then position of
  7899.     the string matching the nth item on the right-hand side of the rule,
  7900.     where n is the integer parameter to lhs_start and lhs_end.  n is 1 for
  7901.     the leftmost item.
  7902.  
  7903. value clear_parser : unit -> unit
  7904.  
  7905.  
  7906. Chapter 14.   The standard library                                         133
  7907.  
  7908.  
  7909.     Empty the parser stack.  Call it just after a parsing function has
  7910.     returned, to remove all pointers from the parser stack to structures that
  7911.     were built by semantic actions during parsing.  This is optional, but
  7912.     lowers the memory requirements of the programs.
  7913.  
  7914. exception Parse_error
  7915.  
  7916.     Raised when a parser encounters a syntax error.
  7917.  
  7918.  
  7919.  
  7920. 14.11 printexc:  a catch-all exception handler
  7921.  
  7922. value f: ('a -> 'b) -> 'a -> 'b
  7923.  
  7924.     printexc__f fn x applies fn to x and returns the result.  If the
  7925.     evaluation of fn x raises any exception, the name of the exception is
  7926.     printed on standard error output, and the programs aborts with exit code
  7927.     2.  Typical use is printexc__f main (), where main, with type unit->unit,
  7928.     is the entry point of a standalone program, to catch and print stray
  7929.     exceptions.  For printexc__f to work properly, the program must have been
  7930.     linked with the -g option.
  7931.  
  7932.  
  7933.  
  7934. 14.12 printf:  formatting printing functions
  7935.  
  7936. type ('a, 'b, 'c) format
  7937.  
  7938.     The type of format strings.  'a is the type of the parameters of the
  7939.     string, 'c is the result type for the printf-style function, and 'b is
  7940.     the type of the first argument given to %a and %t printing functions.
  7941.  
  7942. value fprintf: out_channel -> ('a, out_channel, unit) format -> 'a
  7943.  
  7944.     fprintf outchan format arg1 ... argN formats the arguments arg1 to argN
  7945.     according to the format string format, and outputs the resulting string
  7946.     on the channel outchan.  The format is a character string which contains
  7947.     two types of objects:  plain characters, which are simply copied to the
  7948.     output channel, and conversion specifications, each of which causes
  7949.     conversion and printing of one argument.  Conversion specifications
  7950.     consist in the % character, followed by optional flags and field widths,
  7951.     followed by one conversion character.  The conversion characters and
  7952.     their meanings are:
  7953.     d or i:  convert an integer argument to signed decimal
  7954.     u:  convert an integer argument to unsigned decimal
  7955.     x:  convert an integer argument to unsigned hexadecimal, using lowercase
  7956.     letters.
  7957.     X: convert an integer argument to unsigned hexadecimal, using uppercase
  7958.     letters.
  7959.     s:  insert a string argument
  7960.     c:  insert a character argument
  7961.     f:  convert a floating-point argument to decimal notation, in the style
  7962.     dddd.ddd
  7963.     e or E: convert a floating-point argument to decimal notation, in the
  7964.     style d.ddd e+-dd (mantissa and exponent)
  7965.     g or G: convert a floating-point argument to decimal notation, in style f
  7966.     or e, E (whichever is more compact)
  7967.     b:  convert a boolean argument to the string true or false
  7968.  
  7969.  
  7970. Chapter 14.   The standard library                                         134
  7971.  
  7972.  
  7973.     a:  user-defined printer.  Takes two arguments and apply the first one to
  7974.     outchan (the current output channel) and to the second argument.  The
  7975.     first argument must therefore have type out_channel -> 'b -> unit and the
  7976.     second 'b.  The output produced by the function is therefore inserted in
  7977.     the output of fprintf at the current point.
  7978.     t:  same as %a, but takes only one argument (with type
  7979.     out_channel -> unit) and apply it to outchan.
  7980.     Refer to the C library printf function for the meaning of flags and field
  7981.     width specifiers.  If too few arguments are provided, printing stops just
  7982.     before converting the first missing argument.
  7983.  
  7984. value printf: ('a, out_channel, unit) format -> 'a
  7985.  
  7986.     Same as fprintf, but output on std_out.
  7987.  
  7988. value eprintf: ('a, out_channel, unit) format -> 'a
  7989.  
  7990.     Same as fprintf, but output on std_err.
  7991.  
  7992. value fprint: out_channel -> string -> unit
  7993.  
  7994.     Print the given string on the given output channel, without any
  7995.     formatting.  This is the same function as output_string of module io.
  7996.  
  7997. value print: string -> unit
  7998.  
  7999.     Print the given string on std_out, without any formatting.  This is the
  8000.     same function as print_string of module io.
  8001.  
  8002. value eprint: string -> unit
  8003.  
  8004.     Print the given string on std_err, without any formatting.  This is the
  8005.     same function as prerr_string of module io.
  8006.  
  8007.  
  8008.  
  8009. 14.13 queue:  queues
  8010.  
  8011.     This module implements queues (FIFOs), with in-place modification.
  8012.  
  8013. type 'a t
  8014.  
  8015.     The type of queues containing elements of type 'a.
  8016.  
  8017. exception Empty
  8018.  
  8019.     Raised when take is applied to an empty queue.
  8020.  
  8021. value new: unit -> 'a t
  8022.  
  8023.     Return a new queue, initially empty.
  8024.  
  8025. value add: 'a -> 'a t -> unit
  8026.  
  8027.     add x q adds the element x at the end of the queue q.
  8028.  
  8029.  
  8030. Chapter 14.   The standard library                                         135
  8031.  
  8032.  
  8033. value take: 'a t -> 'a
  8034.  
  8035.     take q removes and returns the first element in queue q, or raises Empty
  8036.     if the queue is empty.
  8037.  
  8038. value peek: 'a t -> 'a
  8039.  
  8040.     peek q returns the first element in queue q, without removing it from the
  8041.     queue, or raises Empty if the queue is empty.
  8042.  
  8043. value clear : 'a t -> unit
  8044.  
  8045.     Discard all elements from a queue.
  8046.  
  8047. value length: 'a t -> int
  8048.  
  8049.     Return the number of elements in a queue.
  8050.  
  8051. value iter: ('a -> 'b) -> 'a t -> unit
  8052.  
  8053.     iter f q applies f in turn to all elements of q, from the least recently
  8054.     entered to the most recently entered.  The queue itself is unchanged.
  8055.  
  8056.  
  8057.  
  8058. 14.14 random:  pseudo-random number generator
  8059.  
  8060. value init : int -> unit
  8061.  
  8062.     Initialize the generator, using the argument as a seed.  The same seed
  8063.     will always yield the same sequence of numbers.
  8064.  
  8065. value full_init : int vect -> unit
  8066.  
  8067.     Same as init but takes more data as seed.  It is not useful to give more
  8068.     than 55 integers.
  8069.  
  8070. value int : int -> int
  8071.  
  8072.     random__int bound returns a random number between 0 (inclusive) and bound
  8073.                                                            30
  8074.     (exclusive).  bound must be positive and smaller than 2  .
  8075.  
  8076. value float : float -> float
  8077.  
  8078.     random__float bound returns a random number between 0 (inclusive) and
  8079.     bound (exclusive).
  8080.  
  8081.  
  8082.  
  8083. 14.15 set:  sets over ordered types
  8084.  
  8085.     This module implements the set data structure, given a total ordering
  8086.     function over the set elements.  All operations over sets are purely
  8087.     applicative (no side-effects).  The implementation uses balanced binary
  8088.     trees, and is therefore reasonably efficient:  insertion and membership
  8089.     take time logarithmic in the size of the set, for instance.
  8090.  
  8091.  
  8092. Chapter 14.   The standard library                                         136
  8093.  
  8094.  
  8095. type 'a t
  8096.  
  8097.     The type of sets containing elements of type 'a.
  8098.  
  8099. value empty: ('a -> 'a -> int) -> 'a t
  8100.  
  8101.     The empty set.  The argument is a total ordering function over the set
  8102.     elements.  This is a two-argument function f such that f e1 e2 is zero if
  8103.     the elements e1 and e2 are equal, f e1 e2 is strictly negative if e1 is
  8104.     smaller than e2, and f e1 e2 is strictly positive if e1 is greater than
  8105.     e2.  Examples:  a suitable ordering function for type int is prefix -.
  8106.     You can also use the generic structural comparison function eq__compare.
  8107.  
  8108. value is_empty: 'a t -> bool
  8109.  
  8110.     Test whether a set is empty or not.
  8111.  
  8112. value mem: 'a -> 'a t -> bool
  8113.  
  8114.     mem x s tests whether x belongs to the set s.
  8115.  
  8116. value add: 'a -> 'a t -> 'a t
  8117.  
  8118.     add x s returns a set containing all elements of s, plus x.  If x was
  8119.     already in s, s is returned unchanged.
  8120.  
  8121. value remove: 'a -> 'a t -> 'a t
  8122.  
  8123.     remove x s returns a set containing all elements of s, except x.  If x
  8124.     was not in s, s is returned unchanged.
  8125.  
  8126. value union: 'a t -> 'a t -> 'a t
  8127. value inter: 'a t -> 'a t -> 'a t
  8128. value diff: 'a t -> 'a t -> 'a t
  8129.  
  8130.     Union, intersection and set difference.
  8131.  
  8132. value equal: 'a t -> 'a t -> bool
  8133.  
  8134.     equal s1 s2 tests whether the sets s1 and s2 are equal, that is, contain
  8135.     the same elements.
  8136.  
  8137. value compare: 'a t -> 'a t -> int
  8138.  
  8139.     Total ordering between sets.  Can be used as the ordering function for
  8140.     doing sets of sets.
  8141.  
  8142. value elements: 'a t -> 'a list
  8143.  
  8144.     Return the list of all elements of the given set.  The elements appear in
  8145.     the list in some non-specified order.
  8146.  
  8147. value iter: ('a -> 'b) -> 'a t -> unit
  8148.  
  8149.     iter f s applies f in turn to all elements of s, and discards the
  8150.     results.  The elements of s are presented to f in a non-specified order.
  8151.  
  8152.  
  8153. Chapter 14.   The standard library                                         137
  8154.  
  8155.  
  8156. value fold: ('a -> 'b -> 'b) -> 'a t -> 'b -> 'b
  8157.  
  8158.     fold f s a computes (f xN ... (f x2 (f x1 a))...), where x1 ... xN are
  8159.     the elements of s.  The order in which elements of s are presented to f
  8160.     is not specified.
  8161.  
  8162. value choose: 'a t -> 'a
  8163.  
  8164.     Return one element of the given set, or raise Not_found if the set is
  8165.     empty.  Which element is chosen is not specified, but equal elements will
  8166.     be chosen for equal sets.
  8167.  
  8168.  
  8169.  
  8170. 14.16 sort:  sorting and merging lists
  8171.  
  8172. value sort : ('a -> 'a -> bool) -> 'a list -> 'a list
  8173.  
  8174.     Sort a list in increasing order according to an ordering predicate.  The
  8175.     predicate should return true if its first argument is less than or equal
  8176.     to its second argument.
  8177.  
  8178. value merge : ('a -> 'a -> bool) -> 'a list -> 'a list -> 'a list
  8179.  
  8180.     Merge two lists according to the given predicate.  Assuming the two
  8181.     argument lists are sorted according to the predicate, merge returns a
  8182.     sorted list containing the elements from the two lists.  The behavior is
  8183.     undefined if the two argument lists were not sorted.
  8184.  
  8185.  
  8186.  
  8187. 14.17 stack:  stacks
  8188.  
  8189.     This module implements stacks (LIFOs), with in-place modification.
  8190.  
  8191. type 'a t
  8192.  
  8193.     The type of stacks containing elements of type 'a.
  8194.  
  8195. exception Empty
  8196.  
  8197.     Raised when pop is applied to an empty stack.
  8198.  
  8199. value new: unit -> 'a t
  8200.  
  8201.     Return a new stack, initially empty.
  8202.  
  8203. value push: 'a -> 'a t -> unit
  8204.  
  8205.     push x s adds the element x at the top of stack s.
  8206.  
  8207. value pop: 'a t -> 'a
  8208.  
  8209.     pop s removes and returns the topmost element in stack s, or raises Empty
  8210.     if the stack is empty.
  8211.  
  8212. value clear : 'a t -> unit
  8213.  
  8214.     Discard all elements from a stack.
  8215.  
  8216.  
  8217. Chapter 14.  The standard library                                          138
  8218.  
  8219.  
  8220. value length: 'a t -> int
  8221.  
  8222.     Return the number of elements in a stack.
  8223.  
  8224. value iter: ('a -> 'b) -> 'a t -> unit
  8225.  
  8226.     iter f s applies f in turn to all elements of s, from the element at the
  8227.     top of the stack to the element at the bottom of the stack.  The stack
  8228.     itself is unchanged.
  8229.  
  8230.  
  8231.  
  8232. 14.18 sys:  system interface
  8233.  
  8234.     This module provides a simple interface to the operating system.
  8235.  
  8236. exception Sys_error of string
  8237.  
  8238.     Raised by some functions in the sys and io modules, when the underlying
  8239.     system calls fail.  The argument to Sys_error is a string describing the
  8240.     error.  The texts of the error messages are implementation-dependent, and
  8241.     should not be relied upon to catch specific system errors.
  8242.  
  8243. value command_line : string vect
  8244.  
  8245.     The command line arguments given to the process.  The first element is
  8246.     the command name used to invoke the program.
  8247.  
  8248. value interactive: bool
  8249.  
  8250.     True if we're running under the toplevel system.  False if we're running
  8251.     as a standalone program.
  8252.  
  8253. type file_perm == int
  8254. value s_irusr : file_perm
  8255. value s_iwusr : file_perm
  8256. value s_ixusr : file_perm
  8257. value s_irgrp : file_perm
  8258. value s_iwgrp : file_perm
  8259. value s_ixgrp : file_perm
  8260. value s_iroth : file_perm
  8261. value s_iwoth : file_perm
  8262. value s_ixoth : file_perm
  8263. value s_isuid : file_perm
  8264. value s_isgid : file_perm
  8265. value s_irall : file_perm
  8266. value s_iwall : file_perm
  8267. value s_ixall : file_perm
  8268.  
  8269.     Access permissions for files.  r is reading permission, w is writing
  8270.     permission, x is execution permission.  usr means permissions for the
  8271.     user owning the file, grp for the group owning the file, oth for others.
  8272.     isuid and isgid are for set-user-id and set-group-id files, respectively.
  8273.     The remaining are combinations of the permissions above.
  8274.  
  8275. type open_flag =
  8276.     O_RDONLY                       (* open read-only *)
  8277.   | O_WRONLY                       (* open write-only *)
  8278.  
  8279.  
  8280. Chapter 14.   The standard library                                         139
  8281.  
  8282.  
  8283.   | O_RDWR                         (* open for reading and writing *)
  8284.   | O_APPEND                       (* open for appending *)
  8285.   | O_CREAT                        (* create the file if nonexistent *)
  8286.   | O_TRUNC                        (* truncate the file to 0 if it exists *)
  8287.   | O_EXCL                         (* fails if the file exists *)
  8288.   | O_BINARY                       (* open in binary mode *)
  8289.   | O_TEXT                         (* open in text mode *)
  8290.  
  8291.     The commands for open.
  8292.  
  8293. value exit : int -> 'a
  8294.  
  8295.     Terminate the program and return the given status code to the operating
  8296.     system.  In contrast with the function exit from module io, this exit
  8297.     function does not flush the standard output and standard error channels.
  8298.  
  8299. value open : string -> open_flag list -> file_perm -> int
  8300.  
  8301.     Open a file.  The second argument is the opening mode.  The third
  8302.     argument is the permissions to use if the file must be created.  The
  8303.     result is a file descriptor opened on the file.
  8304.  
  8305. value close : int -> unit
  8306.  
  8307.     Close a file descriptor.
  8308.  
  8309. value remove : string -> unit
  8310.  
  8311.     Remove the given file name from the file system.
  8312.  
  8313. value rename : string -> string -> unit
  8314.  
  8315.     Rename a file.  The first argument is the old name and the second is the
  8316.     new name.
  8317.  
  8318. value getenv : string -> string
  8319.  
  8320.     Return the value associated to a variable in the process environment.
  8321.     Raise Not_found if the variable is unbound.
  8322.  
  8323. value chdir : string -> unit
  8324.  
  8325.     Change the current working directory of the process.  Note that there is
  8326.     no easy way of getting the current working directory from the operating
  8327.     system.
  8328.  
  8329. value system_command : string -> int
  8330.  
  8331.     Execute the given shell command and return its exit code.
  8332.  
  8333. exception Break
  8334.  
  8335.     Exception Break is raised on user interrupt if catch_break is on.
  8336.  
  8337. value catch_break : bool -> unit
  8338.  
  8339.     catch_break governs whether user interrupt terminates the program or
  8340.     raises the Break exception.  Call catch_break true to enable raising
  8341.  
  8342.  
  8343. Chapter 14.   The standard library                                         140
  8344.  
  8345.  
  8346.     Break, and catch_break false to let the system terminate the program on
  8347.     user interrupt.
  8348.  
  8349.  
  8350.  
  8351.  
  8352.  
  8353.  
  8354.  
  8355.  
  8356.  
  8357.  
  8358.  
  8359. Chapter 15
  8360.  
  8361.  
  8362.  
  8363. The graphics library
  8364.  
  8365.  
  8366.  
  8367. This chapter describes the portable graphics primitives that come standard in
  8368. the implementation of Caml Light on micro-computers.
  8369.  
  8370. Unix: On Unix workstations running the X11 windows system, an implementation
  8371.       of the graphics primitives is available in the directory
  8372.       contrib/libgraph in the distribution.  See the file README in this
  8373.       directory for information on building and using camlgraph, a toplevel
  8374.       system that includes the graphics primitives, and linking standalone
  8375.       programs with the library.  Drawing takes place in a separate window
  8376.       that is created when open_graph is called.
  8377.  
  8378. Mac:  The graphics primitive are available from the standalone application
  8379.       that runs the toplevel system.  They are not available from programs
  8380.       compiled by camlc and run under the MPW shell.  Drawing takes place in
  8381.       a separate window, that can be made visible with the ``Show graphics
  8382.       window'' menu entry.
  8383.  
  8384. PC:   The graphics primitive are available both at toplevel and in separately
  8385.       compiled programs.  The open_graph primitive switches the whole screen
  8386.       to graphics mode.  Under the toplevel system, the user's phrases and
  8387.       the system responses are printed on the graphics screen too, possibly
  8388.       overwriting parts of the drawings, and causing scrolling when the
  8389.       bottom of the screen is reached.
  8390.  
  8391.   The screen coordinates are interpreted as shown in the figure below.  Notice
  8392. that the coordinate system used is the same as in mathematics:  y increases
  8393. from the bottom of the screen to the top of the screen, and angles are
  8394. measured counterclockwisey(in degrees).  Drawing is clipped to the screen.
  8395.                           |
  8396.                          -------------------------
  8397.                 size_y()  |                      |
  8398.                           |               Screen |
  8399.                           |                      |
  8400.                           |                      |
  8401.                           |      |pixel at (x,y) |
  8402.                        y ---------
  8403.                           |      |               |
  8404.                           |      |               |
  8405.                           |      |               |
  8406.                           |      |               |
  8407.                                  |               |
  8408.                         ------------------------------
  8409.                           |      |               |     x
  8410.                           |     x            size_x()
  8411.  
  8412.  
  8413.  
  8414.                                      141
  8415.  
  8416.  
  8417. Chapter 15.   The graphics library                                         142
  8418.  
  8419.  
  8420. Here are the graphics mode specifications supported by open_graph on the
  8421. various implementations of this library.
  8422.  
  8423. Unix: The argument to open_graph has the format "display-name geometry",
  8424.       where display-name is the name of the X-windows display to connect to,
  8425.       and geometry is a standard X-windows geometry specification.  The two
  8426.       components are separated by a space.  Either can be omitted, or both.
  8427.       Examples:
  8428.  
  8429.  
  8430.       open_graph "foo:0"
  8431.           connects to the display foo:0 and creates a window with the default
  8432.           geometry
  8433.  
  8434.       open_graph "foo:0 300x100+50-0"
  8435.           connects to the display foo:0 and creates a window 300 pixels wide
  8436.           by 100 pixels tall, at location (50,0)
  8437.  
  8438.       open_graph " 300x100+50-0"
  8439.           connects to the default display and creates a window 300 pixels
  8440.           wide by 100 pixels tall, at location (50,0)
  8441.  
  8442.       open_graph ""
  8443.           connects to the default display and creates a window with the
  8444.           default geometry.
  8445.  
  8446.  
  8447. Mac:  The argument to open_graph is ignored.
  8448.  
  8449. PC:   The 386 PC version supports VGA graphics cards, and a number of
  8450.       SuperVGA cards, provided the correct driver has been installed.  (See
  8451.       the installation instructions.)  Only 256 color modes are supported.
  8452.       This means a resolution of 320x200 on standard VGA, and from 640x480 to
  8453.       1024x768 on SuperVGA.
  8454.  
  8455.       The graphics primitive do not work if Caml Light runs under Windows 3
  8456.       or any DPMI-compliant memory manager.
  8457.  
  8458.       The argument to open_graph is interpreted as follows:
  8459.  
  8460.           ---------------------------------------------------------------
  8461.           |Argument to open_graph |Graphic mode                          |
  8462.           ---------------------------------------------------------------
  8463.           |"highest"              |highest possible resolution           |
  8464.           |"noninterlaced"        |highest   possible  resolution,  non- |
  8465.           |                       |interlaced mode                       |
  8466.           |"320x200"              |standard 320x200 VGA mode             |
  8467.           |"wxh"                  |at least w by h pixels, if possible   |
  8468.           |anything else          |default  resolution,  as  set in  the |
  8469.           |                       |GO32  variable (see  the installation |
  8470.           |                       |instructions).                        |
  8471.           ---------------------------------------------------------------
  8472.  
  8473.  
  8474. 15.1 graphics:  machine-independent graphics primitives
  8475.  
  8476. exception Graphic_failure of string
  8477.  
  8478.     Raised by the functions below when they encounter an error.
  8479.  
  8480.  
  8481. Chapter 15.  The graphics library                                          143
  8482.  
  8483.  
  8484. Initializations
  8485.  
  8486. value open_graph: string -> unit
  8487.  
  8488.     Show the graphics window or switch the screen to graphic mode.  The
  8489.     graphics window is cleared.  The string argument is used to pass optional
  8490.     information on the desired graphics mode, the graphics window size, and
  8491.     so on.  Its interpretation is implementation-dependent.  If the empty
  8492.     string is given, a sensible default is selected.
  8493.  
  8494. value close_graph: unit -> unit
  8495.  
  8496.     Delete the graphics window or switch the screen back to text mode.
  8497.  
  8498. value clear_graph : unit -> unit
  8499.  
  8500.     Erase the graphics window.
  8501.  
  8502. value size_x : unit -> int
  8503. value size_y : unit -> int
  8504.  
  8505.     Return the size of the graphics window.  Coordinates of the screen pixels
  8506.     range over 0 .. size_x()-1 and 0 .. size_y()-1.  Drawings outside of this
  8507.     rectangle are clipped, without causing an error.  The origin (0,0) is at
  8508.     the lower left corner.
  8509.  
  8510.  
  8511. Colors
  8512.  
  8513. type color == int
  8514.  
  8515.     A color is specified by its R, G, B components.  Each component is in the
  8516.     range 0..255.  The three components are packed in an int:  0xRRGGBB,
  8517.     where RR are the two hexadecimal digits for the red component, GG for the
  8518.     green component, BB for the blue component.
  8519.  
  8520. value rgb: int -> int -> int -> color
  8521.  
  8522.     rgb r g b returns the integer encoding the color with red component r,
  8523.     green component g, and blue component b.  r, g and b are in the range
  8524.     0..255.
  8525.  
  8526. value set_color : color -> unit
  8527.  
  8528.     Set the current drawing color.
  8529.  
  8530. value black : color
  8531. value white : color
  8532. value red : color
  8533. value green : color
  8534. value blue : color
  8535. value yellow : color
  8536. value cyan : color
  8537. value magenta : color
  8538.  
  8539.     Some predefined colors.
  8540.  
  8541.  
  8542. Chapter 15.  The graphics library                                          144
  8543.  
  8544.  
  8545. value background: color
  8546. value foreground: color
  8547.  
  8548.     Default background and foreground colors (usually, either black
  8549.     foreground on a white background or white foreground on a black
  8550.     background).  clear_graph fills the screen with the background color.
  8551.     The initial drawing color is foreground.
  8552.  
  8553.  
  8554. Point and line drawing
  8555.  
  8556. value plot : int -> int -> unit
  8557.  
  8558.     Plot the given point with the current drawing color.
  8559.  
  8560. value point_color : int -> int -> color
  8561.  
  8562.     Return the color of the given point.
  8563.  
  8564. value moveto : int -> int -> unit
  8565.  
  8566.     Position the current point.
  8567.  
  8568. value current_point : unit -> int * int
  8569.  
  8570.     Return the position of the current point.
  8571.  
  8572. value lineto : int -> int -> unit
  8573.  
  8574.     Draw a line with endpoints the current point and the given point, and
  8575.     move the current point to the given point.
  8576.  
  8577. value draw_arc : int -> int -> int -> int -> int -> int -> unit
  8578.  
  8579.     draw_arc x y rx ry a1 a2 draws an elliptical arc with center x,y,
  8580.     horizontal radius rx, vertical radius ry, from angle a1 to angle a2 (in
  8581.     degrees).  The current point is unchanged.
  8582.  
  8583. value draw_ellipse : int -> int -> int -> int -> unit
  8584.  
  8585.     draw_ellipse x y rx ry draws an ellipse with center x,y, horizontal
  8586.     radius rx and vertical radius ry.  The current point is unchanged.
  8587.  
  8588. value draw_circle : int -> int -> int -> unit
  8589.  
  8590.     draw_circle x y r draws a circle with center x,y and radius r.  The
  8591.     current point is unchanged.
  8592.  
  8593. value set_line_width : int -> unit
  8594.  
  8595.     Set the width of points and lines drawn with the functions above.  Under
  8596.     X Windows, set_line_width 0 selects a width of 1 pixel and a faster, but
  8597.     less precise drawing algorithm than the one used when set_line_width 1 is
  8598.     specified.
  8599.  
  8600.  
  8601. Chapter 15.  The graphics library                                          145
  8602.  
  8603.  
  8604. Text drawing
  8605.  
  8606. value draw_char : char -> unit
  8607. value draw_string : string -> unit
  8608.  
  8609.     Draw a character or a character string with lower left corner at current
  8610.     position.  After drawing, the current position is set to the lower right
  8611.     corner of the text drawn.
  8612.  
  8613. value set_font : string -> unit
  8614. value set_text_size : int -> unit
  8615.  
  8616.     Set the font and character size used for drawing text.  The
  8617.     interpretation of the arguments to set_font and set_text_size is
  8618.     implementation-dependent.
  8619.  
  8620. value text_size : string -> int * int
  8621.  
  8622.     Return the dimensions of the given text, if it were drawn with the
  8623.     current font and size.
  8624.  
  8625.  
  8626. Filling
  8627.  
  8628. value fill_rect : int -> int -> int -> int -> unit
  8629.  
  8630.     fill_rect x y w h fills the rectangle with lower left corner at x,y,
  8631.     width w and heigth h, with the current color.
  8632.  
  8633. value fill_poly : (int * int) vect -> unit
  8634.  
  8635.     Fill the given polygon with the current color.  The array contains the
  8636.     coordinates of the vertices of the polygon.
  8637.  
  8638. value fill_arc : int -> int -> int -> int -> int -> int -> unit
  8639.  
  8640.     Fill an elliptical pie slice with the current color.  The parameters are
  8641.     the same as for draw_arc.
  8642.  
  8643. value fill_ellipse : int -> int -> int -> int -> unit
  8644.  
  8645.     Fill an ellipse with the current color.  The parameters are the same as
  8646.     for draw_ellipse.
  8647.  
  8648. value fill_circle : int -> int -> int -> unit
  8649.  
  8650.     Fill a circle with the current color.  The parameters are the same as for
  8651.     draw_circle.
  8652.  
  8653.  
  8654. Images
  8655.  
  8656. type image
  8657.  
  8658.     The abstract type for images, in internal representation.  Externally,
  8659.     images are represented as matrices of colors.
  8660.  
  8661.  
  8662. Chapter 15.   The graphics library                                         146
  8663.  
  8664.  
  8665. value transp : color
  8666.  
  8667.     In matrices of colors, this color represent a ``transparent'' point:
  8668.     when drawing the corresponding image, all pixels on the screen
  8669.     corresponding to a transparent pixel in the image will not be modified,
  8670.     while other points will be set to the color of the corresponding point in
  8671.     the image.  This allows superimposing an image over an existing
  8672.     background.
  8673.  
  8674. value make_image : color vect vect -> image
  8675.  
  8676.     Convert the given color matrix to an image.  Each sub-array represents
  8677.     one horizontal line.  All sub-arrays must have the same length;
  8678.     otherwise, exception Graphic_failure is raised.
  8679.  
  8680. value dump_image : image -> color vect vect
  8681.  
  8682.     Convert an image to a color matrix.
  8683.  
  8684. value draw_image : image -> int -> int -> unit
  8685.  
  8686.     Draw the given image with lower left corner at the given point.
  8687.  
  8688. value get_image : int -> int -> int -> int -> image
  8689.  
  8690.     Capture the contents of a rectangle on the screen as an image.  The
  8691.     parameters are the same as for fill_rect.
  8692.  
  8693. value create_image : int -> int -> image
  8694.  
  8695.     create_image w h returns a new image w pixels wide and h pixels tall, to
  8696.     be used in conjunction with blit_image.  The initial image contents are
  8697.     random.
  8698.  
  8699. value blit_image : image -> int -> int -> unit
  8700.  
  8701.     blit_image img x y copies screen pixels into the image img, modifying img
  8702.     in-place.  The pixels copied are those inside the rectangle with lower
  8703.     left corner at x,y, and width and height equal to those of the image.
  8704.  
  8705.  
  8706. Mouse and keyboard events
  8707.  
  8708. type status =
  8709.   { mouse_x : int;              (* X coordinate of the mouse *)
  8710.     mouse_y : int;              (* Y coordinate of the mouse *)
  8711.     button : bool;              (* true if a mouse button is pressed *)
  8712.     keypressed : bool;          (* true if a key has been pressed *)
  8713.     key : char }                (* the character for the key pressed *)
  8714.  
  8715.     To report events.
  8716.  
  8717. type event =
  8718.     Button_down                 (* A mouse button is pressed *)
  8719.   | Button_up                   (* A mouse button is released *)
  8720.   | Key_pressed                 (* A key is pressed *)
  8721.   | Mouse_motion                (* The mouse is moved *)
  8722.   | Poll                        (* Don't wait; return immediately *)
  8723.  
  8724.  
  8725. Chapter 15.   The graphics library                                         147
  8726.  
  8727.  
  8728.     To specify events to wait for.
  8729.  
  8730. value wait_next_event : event list -> status
  8731.  
  8732.     Wait until one of the events specified in the given event list occurs,
  8733.     and return the status of the mouse and keyboard at that time.  If Poll is
  8734.     given in the event list, return immediately with the current status.  If
  8735.     the mouse cursor is outside of the graphics window, the mouse_x and
  8736.     mouse_y fields of the event are outside the range
  8737.     0..size_x()-1, 0..size_y()-1.  Keypresses are queued, and dequeued one by
  8738.     one when the Key_pressed event is specified.
  8739.  
  8740.  
  8741. Mouse and keyboard polling
  8742.  
  8743. value mouse_pos : unit -> int * int
  8744.  
  8745.     Return the position of the mouse cursor, relative to the graphics window.
  8746.     If the mouse cursor is outside of the graphics window, mouse_pos()
  8747.     returns a point outside of the range 0..size_x()-1, 0..size_y()-1.
  8748.  
  8749. value button_down : unit -> bool
  8750.  
  8751.     Return true if the mouse button is pressed, false otherwise.
  8752.  
  8753. value read_key : unit -> char
  8754.  
  8755.     Wait for a key to be pressed, and return the corresponding character.
  8756.     Keypresses are queued.
  8757.  
  8758. value key_pressed : unit -> bool
  8759.  
  8760.     Return true if a keypress is available; that is, if read_key would not
  8761.     block.
  8762.  
  8763.  
  8764. Sound
  8765.  
  8766. value sound : int -> int -> unit
  8767.  
  8768.     sound freq dur plays a sound at frequency freq (in hertz) for a duration
  8769.     dur (in milliseconds).  On the Macintosh, the frequency is rounded to the
  8770.     nearest note in the equal-tempered scale.
  8771.  
  8772.  
  8773.  
  8774.  
  8775.  
  8776.  
  8777.  
  8778.  
  8779.  
  8780.  
  8781.  
  8782. Chapter 16
  8783.  
  8784.  
  8785.  
  8786. The unix library:  Unix system calls
  8787.  
  8788.  
  8789.  
  8790. The unix library (distributed in contrib/libunix) makes many Unix system calls
  8791. and system-related library functions available to Caml Light programs.  This
  8792. chapter describes briefly the functions provided.  Refer to sections 2 and 3
  8793. of the Unix manual for more details on the behavior of these functions.
  8794.   Not all functions are provided by all Unix variants.  If some functions are
  8795. not available, they will raise Invalid_arg when called.
  8796.   Programs that use the unix library must be linked in ``custom runtime''
  8797. mode, as follows:
  8798.  
  8799.         camlc -custom other options unix.zo other files -lunix
  8800.  
  8801. For interactive use of the unix library, run camllight camlunix.
  8802.  
  8803. Mac:  This library is not available.
  8804.  
  8805. PC:   This library is not available.
  8806.  
  8807.  
  8808. 16.1 unix:  interface to the Unix system
  8809.  
  8810. Error report
  8811.  
  8812. type error =
  8813.     ENOERR
  8814.   | EPERM               (* Not owner *)
  8815.   | ENOENT              (* No such file or directory *)
  8816.   | ESRCH               (* No such process *)
  8817.   | EINTR               (* Interrupted system call *)
  8818.   | EIO                 (* I/O error *)
  8819.   | ENXIO               (* No such device or address *)
  8820.   | E2BIG               (* Arg list too long *)
  8821.   | ENOEXEC             (* Exec format error *)
  8822.   | EBADF               (* Bad file number *)
  8823.   | ECHILD              (* No children *)
  8824.   | EAGAIN              (* No more processes *)
  8825.   | ENOMEM              (* Not enough core *)
  8826.   | EACCES              (* Permission denied *)
  8827.   | EFAULT              (* Bad address *)
  8828.   | ENOTBLK             (* Block device required *)
  8829.   | EBUSY               (* Mount device busy *)
  8830.   | EEXIST              (* File exists *)
  8831.   | EXDEV               (* Cross-device link *)
  8832.   | ENODEV              (* No such device *)
  8833.  
  8834.  
  8835.                                      148
  8836.  
  8837.  
  8838. Chapter 16.   The unix library:  Unix system calls                         149
  8839.  
  8840.  
  8841.   | ENOTDIR             (* Not a directory*)
  8842.   | EISDIR              (* Is a directory *)
  8843.   | EINVAL              (* Invalid argument *)
  8844.   | ENFILE              (* File table overflow *)
  8845.   | EMFILE              (* Too many open files *)
  8846.   | ENOTTY              (* Not a typewriter *)
  8847.   | ETXTBSY             (* Text file busy *)
  8848.   | EFBIG               (* File too large *)
  8849.   | ENOSPC              (* No space left on device *)
  8850.   | ESPIPE              (* Illegal seek *)
  8851.   | EROFS               (* Read-only file system *)
  8852.   | EMLINK              (* Too many links *)
  8853.   | EPIPE               (* Broken pipe *)
  8854.   | EDOM                (* Argument too large *)
  8855.   | ERANGE              (* Result too large *)
  8856.   | EWOULDBLOCK         (* Operation would block *)
  8857.   | EINPROGRESS         (* Operation now in progress *)
  8858.   | EALREADY            (* Operation already in progress *)
  8859.   | ENOTSOCK            (* Socket operation on non-socket *)
  8860.   | EDESTADDRREQ        (* Destination address required *)
  8861.   | EMSGSIZE            (* Message too long *)
  8862.   | EPROTOTYPE          (* Protocol wrong type for socket *)
  8863.   | ENOPROTOOPT         (* Protocol not available *)
  8864.   | EPROTONOSUPPORT     (* Protocol not supported *)
  8865.   | ESOCKTNOSUPPORT     (* Socket type not supported *)
  8866.   | EOPNOTSUPP          (* Operation not supported on socket *)
  8867.   | EPFNOSUPPORT        (* Protocol family not supported *)
  8868.   | EAFNOSUPPORT        (* Address family not supported by protocol family *)
  8869.   | EADDRINUSE          (* Address already in use *)
  8870.   | EADDRNOTAVAIL       (* Can't assign requested address *)
  8871.   | ENETDOWN            (* Network is down *)
  8872.   | ENETUNREACH         (* Network is unreachable *)
  8873.   | ENETRESET           (* Network dropped connection on reset *)
  8874.   | ECONNABORTED        (* Software caused connection abort *)
  8875.   | ECONNRESET          (* Connection reset by peer *)
  8876.   | ENOBUFS             (* No buffer space available *)
  8877.   | EISCONN             (* Socket is already connected *)
  8878.   | ENOTCONN            (* Socket is not connected *)
  8879.   | ESHUTDOWN           (* Can't send after socket shutdown *)
  8880.   | ETOOMANYREFS        (* Too many references: can't splice *)
  8881.   | ETIMEDOUT           (* Connection timed out *)
  8882.   | ECONNREFUSED        (* Connection refused *)
  8883.   | ELOOP               (* Too many levels of symbolic links *)
  8884.   | ENAMETOOLONG        (* File name too long *)
  8885.   | EHOSTDOWN           (* Host is down *)
  8886.   | EHOSTUNREACH        (* No route to host *)
  8887.   | ENOTEMPTY           (* Directory not empty *)
  8888.   | EPROCLIM            (* Too many processes *)
  8889.   | EUSERS              (* Too many users *)
  8890.   | EDQUOT              (* Disc quota exceeded *)
  8891.   | ESTALE              (* Stale NFS file handle *)
  8892.   | EREMOTE             (* Too many levels of remote in path *)
  8893.   | EIDRM               (* Identifier removed *)
  8894.   | EDEADLK             (* Deadlock condition. *)
  8895.   | ENOLCK              (* No record locks available. *)
  8896.   | ENOSYS              (* Function not implemented *)
  8897.   | EUNKNOWNERR
  8898.  
  8899.  
  8900. Chapter 16.   The unix library:  Unix system calls                         150
  8901.  
  8902.  
  8903.     The type of error codes.
  8904.  
  8905. exception Unix_error of error * string * string
  8906.  
  8907.     Raised by the system calls below when an error is encountered.  The first
  8908.     component is the error code; the second component is the function name;
  8909.     the third component is the string parameter to the function, if it has
  8910.     one, or the empty string otherwise.
  8911.  
  8912. value error_message : error -> string
  8913.  
  8914.     Return a string describing the given error code.
  8915.  
  8916. value handle_unix_error : ('a -> 'b) -> 'a -> 'b
  8917.  
  8918.     handle_unix_error f x applies f to x and returns the result.  If the
  8919.     exception Unix_error is raised, it prints a message describing the error
  8920.     and exits with code 2.
  8921.  
  8922.  
  8923. Interface with the parent process
  8924.  
  8925. value environment : unit -> string vect
  8926.  
  8927.     Return the process environment, as an array of strings with the format
  8928.     ``variable=value''.  See also sys__getenv.
  8929.  
  8930.  
  8931. Process handling
  8932.  
  8933. type process_status =
  8934.     WEXITED of int
  8935.   | WSIGNALED of int * bool
  8936.   | WSTOPPED of int
  8937.  
  8938.     The termination status of a process.  WEXITED means that the process
  8939.     terminated normally by exit; the argument is the return code.  WSIGNALED
  8940.     means that the process was killed by a signal; the first argument is the
  8941.     signal number, the second argument indicates whether a ``core dump'' was
  8942.     performed.  WSTOPPED means that the process was stopped by a signal; the
  8943.     argument is the signal number.
  8944.  
  8945. type wait_flag =
  8946.     WNOHANG
  8947.   | WUNTRACED
  8948.  
  8949.     Flags for waitopt and waitpid.  WNOHANG means do not block if no child
  8950.     has died yet, but immediately return with a pid equal to 0.  WUNTRACED
  8951.     means report also the children that receive stop signals.
  8952.  
  8953. value execv : string -> string vect -> unit
  8954.  
  8955.     execv prog args execute the program in file prog, with the arguments
  8956.     args, and the current process environment.
  8957.  
  8958. value execve : string -> string vect -> string vect -> unit
  8959.  
  8960.  
  8961. Chapter 16.  The unix library: Unix system calls                           151
  8962.  
  8963.  
  8964.     Same as execv, except that the third argument provides the environment to
  8965.     the program executed.
  8966.  
  8967. value execvp : string -> string vect -> unit
  8968.  
  8969.     Same as execv, except that the program is searched in the path.
  8970.  
  8971. value fork : unit -> int
  8972.  
  8973.     Fork a new process.  The returned integer is 0 for the child process, the
  8974.     pid of the child process for the parent process.
  8975.  
  8976. value wait : unit -> int * process_status
  8977.  
  8978.     Wait until one of the children processes die, and return its pid and
  8979.     termination status.
  8980.  
  8981. value waitopt : wait_flag list -> int * process_status
  8982.  
  8983.     Same as wait, but takes a list of options to avoid blocking, or also
  8984.     report stopped children.  The pid returned is 0 if no child has changed
  8985.     status.
  8986.  
  8987. value waitpid : wait_flag list -> int -> int * process_status
  8988.  
  8989.     Same as waitopt, but waits for the process whose pid is given.  Negative
  8990.     pid arguments represent process groups.
  8991.  
  8992. value system : string -> process_status
  8993.  
  8994.     Execute the given command, wait until it terminates, and return its
  8995.     termination status.  The string is interpreted by the shell /bin/sh and
  8996.     therefore can contain redirections, quotes, variables, etc.  The result
  8997.     WEXITED 127 indicates that the shell couldn't be executed.
  8998.  
  8999. value getpid : unit -> int
  9000.  
  9001.     Return the pid of the process.
  9002.  
  9003. value getppid : unit -> int
  9004.  
  9005.     Return the pid of the parent process.
  9006.  
  9007. value nice : int -> int
  9008.  
  9009.     Change the process priority.  The integer argument is added to the
  9010.     ``nice'' value.  (Higher values of the ``nice'' value mean lower
  9011.     priorities.)  Return the new nice value.
  9012.  
  9013.  
  9014. Basic file input/output
  9015.  
  9016. type file_descr
  9017.  
  9018.     The abstract type of file descriptors.
  9019.  
  9020.  
  9021. Chapter 16.   The unix library:  Unix system calls                         152
  9022.  
  9023.  
  9024. value stdin : file_descr
  9025. value stdout : file_descr
  9026. value stderr : file_descr
  9027.  
  9028.     File descriptors for standard input, standard output and standard error.
  9029.  
  9030. type open_flag =
  9031.     O_RDONLY                            (* Open for reading *)
  9032.   | O_WRONLY                            (* Open for writing *)
  9033.   | O_RDWR                              (* Open for reading and writing *)
  9034.   | O_NDELAY                            (* Open in non-blocking mode *)
  9035.   | O_APPEND                            (* Open for append *)
  9036.   | O_CREAT                             (* Create if nonexistent *)
  9037.   | O_TRUNC                             (* Truncate to 0 length if existing *)
  9038.   | O_EXCL                              (* Fail if existing *)
  9039.  
  9040.     The flags to open.
  9041.  
  9042. type file_perm == int
  9043.  
  9044.     The type of file access rights.
  9045.  
  9046. value open : string -> open_flag list -> file_perm -> file_descr
  9047.  
  9048.     Open the named file with the given flags.  Third argument is the
  9049.     permissions to give to the file if it is created.  Return a file
  9050.     descriptor on the named file.
  9051.  
  9052. value close : file_descr -> unit
  9053.  
  9054.     Close a file descriptor.
  9055.  
  9056. value read : file_descr -> string -> int -> int -> int
  9057.  
  9058.     read fd buff start len reads len characters from descriptor fd, storing
  9059.     them in string buff, starting at position ofs in string buff.  Return the
  9060.     number of characters actually read.
  9061.  
  9062. value write : file_descr -> string -> int -> int -> int
  9063.  
  9064.     write fd buff start len writes len characters to descriptor fd, taking
  9065.     them from string buff, starting at position ofs in string buff.  Return
  9066.     the number of characters actually written.
  9067.  
  9068.  
  9069. Interfacing with the standard input/output library (module io).
  9070.  
  9071. value in_channel_of_descr : file_descr -> in_channel
  9072.  
  9073.     Create an input channel reading from the given descriptor.
  9074.  
  9075. value out_channel_of_descr : file_descr -> out_channel
  9076.  
  9077.     Create an output channel writing on the given descriptor.
  9078.  
  9079. value descr_of_in_channel : in_channel -> file_descr
  9080.  
  9081.     Return the descriptor corresponding to an input channel.
  9082.  
  9083.  
  9084. Chapter 16.   The unix library:  Unix system calls                         153
  9085.  
  9086.  
  9087. value descr_of_out_channel : out_channel -> file_descr
  9088.  
  9089.     Return the descriptor corresponding to an output channel.
  9090.  
  9091.  
  9092. Seeking and truncating
  9093.  
  9094. type seek_command =
  9095.     SEEK_SET
  9096.   | SEEK_CUR
  9097.   | SEEK_END
  9098.  
  9099.     Positioning modes for lseek.  SEEK_SET indicates positions relative to
  9100.     the beginning of the file, SEEK_CUR relative to the current position,
  9101.     SEEK_END relative to the end of the file.
  9102.  
  9103. value lseek : file_descr -> int -> seek_command -> int
  9104.  
  9105.     Set the current position for a file descriptor
  9106.  
  9107. value truncate : string -> int -> unit
  9108.  
  9109.     Truncates the named file to the given size.
  9110.  
  9111. value ftruncate : file_descr -> int -> unit
  9112.  
  9113.     Truncates the file corresponding to the given descriptor to the given
  9114.     size.
  9115.  
  9116.  
  9117. File statistics
  9118.  
  9119. type file_kind =
  9120.     S_REG                               (* Regular file *)
  9121.   | S_DIR                               (* Directory *)
  9122.   | S_CHR                               (* Character device *)
  9123.   | S_BLK                               (* Block device *)
  9124.   | S_LNK                               (* Symbolic link *)
  9125.   | S_FIFO                              (* Named pipe *)
  9126.   | S_SOCK                              (* Socket *)
  9127. type stats =
  9128.   { st_dev : int;                       (* Device number *)
  9129.     st_ino : int;                       (* Inode number *)
  9130.     st_kind : file_kind;                (* Kind of the file *)
  9131.     st_perm : file_perm;                (* Access rights *)
  9132.     st_nlink : int;                     (* Number of links *)
  9133.     st_uid : int;                       (* User id of the owner *)
  9134.     st_gid : int;                       (* Group id of the owner *)
  9135.     st_rdev : int;                      (* Device minor number *)
  9136.     st_size : int;                      (* Size in bytes *)
  9137.     st_atime : int;                     (* Last access time *)
  9138.     st_mtime : int;                     (* Last modification time *)
  9139.     st_ctime : int }                    (* Last status change time *)
  9140.  
  9141.     The informations returned by the stat calls.
  9142.  
  9143. value stat : string -> stats
  9144.  
  9145.  
  9146. Chapter 16.  The unix library: Unix system calls                           154
  9147.  
  9148.  
  9149.     Return the information for the named file.
  9150.  
  9151. value lstat : string -> stats
  9152.  
  9153.     Same as stat, but in case the file is a symbolic link, return the
  9154.     information for the link itself.
  9155.  
  9156. value fstat : file_descr -> stats
  9157.  
  9158.     Return the information for the file associated with the given descriptor.
  9159.  
  9160.  
  9161. Operations on file names
  9162.  
  9163. value unlink : string -> unit
  9164.  
  9165.     Removes the named file
  9166.  
  9167. value rename : string -> string -> unit
  9168.  
  9169.     rename old new changes the name of a file from old to new.
  9170.  
  9171. value link : string -> string -> unit
  9172.  
  9173.     link source dest creates a hard link named dest to the file named new.
  9174.  
  9175.  
  9176. File permissions and ownership
  9177.  
  9178. type access_permission =
  9179.     R_OK                                (* Read permission *)
  9180.   | W_OK                                (* Write permission *)
  9181.   | X_OK                                (* Execution permission *)
  9182.   | F_OK                                (* File exists *)
  9183.  
  9184.     Flags for the access call.
  9185.  
  9186. value chmod : string -> file_perm -> unit
  9187.  
  9188.     Change the permissions of the named file.
  9189.  
  9190. value fchmod : file_descr -> file_perm -> unit
  9191.  
  9192.     Change the permissions of an opened file.
  9193.  
  9194. value chown : string -> int -> int -> unit
  9195.  
  9196.     Change the owner uid and owner gid of the named file.
  9197.  
  9198. value fchown : file_descr -> int -> int -> unit
  9199.  
  9200.     Change the owner uid and owner gid of an opened file.
  9201.  
  9202. value umask : int -> int
  9203.  
  9204.     Set the process creation mask, and return the previous mask.
  9205.  
  9206.  
  9207. Chapter 16.   The unix library:  Unix system calls                         155
  9208.  
  9209.  
  9210. value access : string -> access_permission list -> unit
  9211.  
  9212.     Check that the process has the given permissions over the named file.
  9213.     Raise Unix_error otherwise.
  9214.  
  9215.  
  9216. File descriptor hacking
  9217.  
  9218. value fcntl_int : file_descr -> int -> int -> int
  9219.  
  9220.     Interface to fcntl in the case where the argument is an integer.  The
  9221.     first integer argument is the command code; the second is the integer
  9222.     parameter.
  9223.  
  9224. value fcntl_ptr : file_descr -> int -> string -> int
  9225.  
  9226.     Interface to fcntl in the case where the argument is a pointer.  The
  9227.     integer argument is the command code.  A pointer to the string argument
  9228.     is passed as argument to the command.
  9229.  
  9230.  
  9231. Directories
  9232.  
  9233. value mkdir : string -> file_perm -> unit
  9234.  
  9235.     Create a directory with the given permissions.
  9236.  
  9237. value rmdir : string -> unit
  9238.  
  9239.     Remove an empty directory.
  9240.  
  9241. value chdir : string -> unit
  9242.  
  9243.     Change the process working directory.
  9244.  
  9245. value getcwd : unit -> string
  9246.  
  9247.     Return the name of the current working directory.
  9248.  
  9249. type dir_handle
  9250.  
  9251.     The type of descriptors over opened directories.
  9252.  
  9253. value opendir : string -> dir_handle
  9254.  
  9255.     Open a descriptor on a directory
  9256.  
  9257. value readdir : dir_handle -> string
  9258.  
  9259.     Return the next entry in a directory.  Raise End_of_file when the end of
  9260.     the directory has been reached.
  9261.  
  9262. value rewinddir : dir_handle -> unit
  9263.  
  9264.     Reposition the descriptor to the beginning of the directory
  9265.  
  9266.  
  9267. Chapter 16.   The unix library:  Unix system calls                         156
  9268.  
  9269.  
  9270. value closedir : dir_handle -> unit
  9271.  
  9272.     Close a directory descriptor.
  9273.  
  9274.  
  9275. Pipes and redirections
  9276.  
  9277. value pipe : unit -> file_descr * file_descr
  9278.  
  9279.     Create a pipe.  The first component of the result is opened for reading,
  9280.     that's the exit to the pipe.  The second component is opened for writing,
  9281.     that's the entrace to the pipe.
  9282.  
  9283. value dup : file_descr -> file_descr
  9284.  
  9285.     Duplicate a descriptor.
  9286.  
  9287. value dup2 : file_descr -> file_descr -> unit
  9288.  
  9289.     dup2 fd1 fd2 duplicates fd1 to fd2, closing fd2 if already opened.
  9290.  
  9291. value open_process_in: string -> in_channel
  9292. value open_process_out: string -> out_channel
  9293. value open_process: string -> in_channel * out_channel
  9294.  
  9295.     High-level pipe and process management.  These functions run the given
  9296.     command in parallel with the program, and return channels connected to
  9297.     the standard input and/or the standard output of the command.  The
  9298.     command is interpreted by the shell /bin/sh (cf.  system).  Warning:
  9299.     writes on channels are buffered, hence be careful to call flush at the
  9300.     right times to ensure correct synchronization.
  9301.  
  9302. value close_process_in: in_channel -> process_status
  9303. value close_process_out: out_channel -> process_status
  9304. value close_process: in_channel * out_channel -> process_status
  9305.  
  9306.     Close channels opened by open_process_in, open_process_out and
  9307.     open_process, respectively, wait for the associated command to terminate,
  9308.     and return its termination status.
  9309.  
  9310.  
  9311. Symbolic links
  9312.  
  9313. value symlink : string -> string -> unit
  9314.  
  9315.     symlink source dest creates the file dest as a symbolic link to the file
  9316.     source.
  9317.  
  9318. value readlink : string -> string
  9319.  
  9320.     Read the contents of a link.
  9321.  
  9322.  
  9323. Named pipes
  9324.  
  9325. value mkfifo : string -> file_perm -> unit
  9326.  
  9327.  
  9328. Chapter 16.  The unix library: Unix system calls                           157
  9329.  
  9330.  
  9331.     Create a named pipe with the given permissions.
  9332.  
  9333.  
  9334. Special files
  9335.  
  9336. value ioctl_int : file_descr -> int -> int -> int
  9337.  
  9338.     Interface to ioctl in the case where the argument is an integer.  The
  9339.     first integer argument is the command code; the second is the integer
  9340.     parameter.
  9341.  
  9342. value ioctl_ptr : file_descr -> int -> string -> int
  9343.  
  9344.     Interface to ioctl in the case where the argument is a pointer.  The
  9345.     integer argument is the command code.  A pointer to the string argument
  9346.     is passed as argument to the command.
  9347.  
  9348.  
  9349. Polling
  9350.  
  9351. value select :
  9352.   file_descr list -> file_descr list -> file_descr list -> float ->
  9353.         file_descr list * file_descr list * file_descr list
  9354.  
  9355.     Wait until some input/output operations become possible on some channels.
  9356.     The three list arguments are, respectively, a set of descriptors to check
  9357.     for reading (first argument), for writing (second argument), or for
  9358.     exceptional conditions (third argument).  The fourth argument is the
  9359.     maximal timeout, in seconds; a negative fourth argument means no timeout
  9360.     (unbounded wait).  The result is composed of three sets of descriptors:
  9361.     those ready for reading (first component), ready for writing (second
  9362.     component), and over which an exceptional condition is pending (third
  9363.     component).
  9364.  
  9365.  
  9366. Locking
  9367.  
  9368. type lock_command =
  9369.     F_ULOCK               (* Unlock a region *)
  9370.   | F_LOCK                (* Lock a region, and block if already locked *)
  9371.   | F_TLOCK               (* Lock a region, or fail if already locked *)
  9372.   | F_TEST                (* Test a region for other process' locks *)
  9373.  
  9374.     Commands for lockf.
  9375.  
  9376. value lockf : file_descr -> lock_command -> int -> unit
  9377.  
  9378.     lockf fd cmd size puts a lock on a region of the file opened as fd.  The
  9379.     region starts at the current read/write position for fd (as set by
  9380.     lseek), and extends size bytes forward if size is positive, size bytes
  9381.     backwards if size is negative, or to the end of the file if size is zero.
  9382.  
  9383.  
  9384. Signals
  9385.  
  9386. type signal =
  9387.     SIGHUP              (* hangup *)
  9388.  
  9389.  
  9390. Chapter 16.  The unix library: Unix system calls                           158
  9391.  
  9392.  
  9393.   | SIGINT              (* interrupt *)
  9394.   | SIGQUIT             (* quit *)
  9395.   | SIGILL              (* illegal instruction (not reset when caught) *)
  9396.   | SIGTRAP             (* trace trap (not reset when caught) *)
  9397.   | SIGABRT             (* used by abort *)
  9398.   | SIGEMT              (* EMT instruction *)
  9399.   | SIGFPE              (* floating point exception *)
  9400.   | SIGKILL             (* kill (cannot be caught or ignored) *)
  9401.   | SIGBUS              (* bus error *)
  9402.   | SIGSEGV             (* segmentation violation *)
  9403.   | SIGSYS              (* bad argument to system call *)
  9404.   | SIGPIPE             (* write on a pipe with no one to read it *)
  9405.   | SIGALRM             (* alarm clock *)
  9406.   | SIGTERM             (* software termination signal from kill *)
  9407.   | SIGURG              (* urgent condition on IO channel *)
  9408.   | SIGSTOP             (* sendable stop signal not from tty *)
  9409.   | SIGTSTP             (* stop signal from tty *)
  9410.   | SIGCONT             (* continue a stopped process *)
  9411.   | SIGCHLD             (* to parent on child stop or exit *)
  9412.   | SIGIO               (* input/output possible signal *)
  9413.   | SIGXCPU             (* exceeded CPU time limit *)
  9414.   | SIGXFSZ             (* exceeded file size limit *)
  9415.   | SIGVTALRM           (* virtual time alarm *)
  9416.   | SIGPROF             (* profiling time alarm *)
  9417.   | SIGWINCH            (* window changed *)
  9418.   | SIGLOST             (* resource lost (eg, record-lock lost) *)
  9419.   | SIGUSR1             (* user defined signal 1 *)
  9420.   | SIGUSR2             (* user defined signal 2 *)
  9421.  
  9422.     The type of signals.
  9423.  
  9424. type signal_handler =
  9425.     Signal_default                      (* Default behavior for the signal *)
  9426.   | Signal_ignore                       (* Ignore the signal *)
  9427.   | Signal_handle of (unit -> unit)     (* Call the given function
  9428.                                            when the signal occurs. *)
  9429.  
  9430.     The behavior on receipt of a signal
  9431.  
  9432. value kill : int -> signal -> unit
  9433.  
  9434.     Send a signal to the process with the given process id.
  9435.  
  9436. value signal : signal -> signal_handler -> unit
  9437.  
  9438.     Set the behavior to be taken on receipt of the given signal.
  9439.  
  9440. value pause : unit -> unit
  9441.  
  9442.     Wait until a non-ignored signal is delivered.
  9443.  
  9444.  
  9445. Time functions
  9446.  
  9447. type process_times =
  9448.   { tms_utime : float;          (* User time for the process *)
  9449.     tms_stime : float;          (* System time for the process *)
  9450.     tms_cutime : float;         (* User time for the children processes *)
  9451.  
  9452.  
  9453. Chapter 16.   The unix library:  Unix system calls                         159
  9454.  
  9455.  
  9456.     tms_cstime : float }        (* System time for the children processes *)
  9457.  
  9458.     The execution times (CPU times) of a process.
  9459.  
  9460. type tm =
  9461.   { tm_sec : int;                       (* Seconds 0..59 *)
  9462.     tm_min : int;                       (* Minutes 0..59 *)
  9463.     tm_hour : int;                      (* Hours 0..23 *)
  9464.     tm_mday : int;                      (* Day of month 1..31 *)
  9465.     tm_mon : int;                       (* Month of year 0..11 *)
  9466.     tm_year : int;                      (* Year - 1900 *)
  9467.     tm_wday : int;                      (* Day of week (Sunday is 0) *)
  9468.     tm_yday : int;                      (* Day of year 0..365 *)
  9469.     tm_isdst : bool }                   (* Daylight time savings in effect *)
  9470.  
  9471.     The type representing wallclock time and calendar date.
  9472.  
  9473. value time : unit -> int
  9474.  
  9475.     Return the current time since 00:00:00 GMT, Jan.  1, 1970, in seconds.
  9476.  
  9477. value gmtime : int -> tm
  9478.  
  9479.     Convert a time in seconds, as returned by time, into a date and a time.
  9480.     Assumes Greenwich meridian time zone.
  9481.  
  9482. value localtime : int -> tm
  9483.  
  9484.     Convert a time in seconds, as returned by time, into a date and a time.
  9485.     Assumes the local time zone.
  9486.  
  9487. value alarm : int -> int
  9488.  
  9489.     Schedule a SIGALRM signals after the given number of seconds.
  9490.  
  9491. value sleep : int -> unit
  9492.  
  9493.     Stop execution for the given number of seconds.
  9494.  
  9495. value times : unit -> process_times
  9496.  
  9497.     Return the execution times of the process.
  9498.  
  9499. value utimes : string -> int -> int -> unit
  9500.  
  9501.     Set the last access time (second arg) and last modification time (third
  9502.     arg) for a file.  Times are expressed in seconds from 00:00:00 GMT, Jan.
  9503.     1, 1970.
  9504.  
  9505.  
  9506. User id, group id
  9507.  
  9508. value getuid : unit -> int
  9509.  
  9510.     Return the user id of the user executing the process.
  9511.  
  9512.  
  9513. Chapter 16.   The unix library:  Unix system calls                         160
  9514.  
  9515.  
  9516. value geteuid : unit -> int
  9517.  
  9518.     Return the effective user id under which the process runs.
  9519.  
  9520. value setuid : int -> unit
  9521.  
  9522.     Set the real user id and effective user id for the process.
  9523.  
  9524. value getgid : unit -> int
  9525.  
  9526.     Return the group id of the user executing the process.
  9527.  
  9528. value getegid : unit -> int
  9529.  
  9530.     Return the effective group id under which the process runs.
  9531.  
  9532. value setgid : int -> unit
  9533.  
  9534.     Set the real group id and effective group id for the process.
  9535.  
  9536. value getgroups : unit -> int vect
  9537.  
  9538.     Return the list of groups to which the user executing the process
  9539.     belongs.
  9540.  
  9541. type passwd_entry =
  9542.   { pw_name : string;
  9543.     pw_passwd : string;
  9544.     pw_uid : int;
  9545.     pw_gid : int;
  9546.     pw_gecos : string;
  9547.     pw_dir : string;
  9548.     pw_shell : string }
  9549.  
  9550.     Structure of entries in the passwd database.
  9551.  
  9552. type group_entry =
  9553.   { gr_name : string;
  9554.     gr_passwd : string;
  9555.     gr_gid : int;
  9556.     gr_mem : string vect }
  9557.  
  9558.     Structure of entries in the groups database.
  9559.  
  9560. value getlogin : unit -> string
  9561.  
  9562.     Return the login name of the user executing the process.
  9563.  
  9564. value getpwnam : string -> passwd_entry
  9565.  
  9566.     Find an entry in passwd with the given name, or raise Not_found.
  9567.  
  9568. value getgrnam : string -> group_entry
  9569.  
  9570.     Find an entry in group with the given name, or raise Not_found.
  9571.  
  9572.  
  9573. Chapter 16.  The unix library: Unix system calls                           161
  9574.  
  9575.  
  9576. value getpwuid : int -> passwd_entry
  9577.  
  9578.     Find an entry in passwd with the given user id, or raise Not_found.
  9579.  
  9580. value getgrgid : int -> group_entry
  9581.  
  9582.     Find an entry in group with the given group id, or raise Not_found.
  9583.  
  9584.  
  9585. Internet addresses
  9586.  
  9587. type inet_addr
  9588.  
  9589.     The abstract type of Internet addresses.
  9590.  
  9591. value inet_addr_of_string : string -> inet_addr
  9592. value string_of_inet_addr : inet_addr -> string
  9593.  
  9594.     Conversions between string with the format XXX.YYY.ZZZ.TTT and Internet
  9595.     addresses.  inet_addr_of_string raises Failure when given a string that
  9596.     does not match this format.
  9597.  
  9598.  
  9599. Sockets
  9600.  
  9601. type socket_domain =
  9602.     PF_UNIX                             (* Unix domain *)
  9603.   | PF_INET                             (* Internet domain *)
  9604.  
  9605.     The type of socket domains.
  9606.  
  9607. type socket_type =
  9608.     SOCK_STREAM                         (* Stream socket *)
  9609.   | SOCK_DGRAM                          (* Datagram socket *)
  9610.   | SOCK_RAW                            (* Raw socket *)
  9611.   | SOCK_SEQPACKET                      (* Sequenced packets socket *)
  9612.  
  9613.     The type of socket kinds, specifying the semantics of communications.
  9614.  
  9615. type sockaddr =
  9616.     ADDR_UNIX of string
  9617.   | ADDR_INET of inet_addr * int
  9618.  
  9619.     The type of socket addresses.  ADDR_UNIX name is a socket address in the
  9620.     Unix domain; name is a file name in the file system.
  9621.     ADDR_INET(addr,port) is a socket address in the Internet domain; addr is
  9622.     the Internet address of the machine, and port is the port number.
  9623.  
  9624. type shutdown_command =
  9625.     SHUTDOWN_RECEIVE                    (* Close for receiving *)
  9626.   | SHUTDOWN_SEND                       (* Close for sending *)
  9627.   | SHUTDOWN_ALL                        (* Close both *)
  9628.  
  9629.     The type of commands for shutdown.
  9630.  
  9631. type msg_flag =
  9632.     MSG_OOB
  9633.  
  9634.  
  9635. Chapter 16.  The unix library: Unix system calls                           162
  9636.  
  9637.  
  9638.   | MSG_DONTROUTE
  9639.   | MSG_PEEK
  9640.  
  9641.     The flags for recv, recvfrom, send and sendto.
  9642.  
  9643. value socket : socket_domain -> socket_type -> int -> file_descr
  9644.  
  9645.     Create a new socket in the given domain, and with the given kind.  The
  9646.     third argument is the protocol type; 0 selects the default protocol for
  9647.     that kind of sockets.
  9648.  
  9649. value socketpair :
  9650.         socket_domain -> socket_type -> int -> file_descr * file_descr
  9651.  
  9652.     Create a pair of unnamed sockets, connected together.
  9653.  
  9654. value accept : file_descr -> file_descr * sockaddr
  9655.  
  9656.     Accept connections on the given socket.  The returned descriptor is a
  9657.     socket connected to the client; the returned address is the address of
  9658.     the connecting client.
  9659.  
  9660. value bind : file_descr -> sockaddr -> unit
  9661.  
  9662.     Bind a socket to an address.
  9663.  
  9664. value connect : file_descr -> sockaddr -> unit
  9665.  
  9666.     Connect a socket to an address.
  9667.  
  9668. value listen : file_descr -> int -> unit
  9669.  
  9670.     Set up a socket for receiving connection requests.  The integer argument
  9671.     is the maximal number of pending requests.
  9672.  
  9673. value shutdown : file_descr -> shutdown_command -> unit
  9674.  
  9675.     Shutdown a socket connection.  SHUTDOWN_SEND as second argument causes
  9676.     reads on the other end of the connection to return an end-of-file
  9677.     condition.  SHUTDOWN_RECEIVE causes writes on the other end of the
  9678.     connection to return a closed pipe condition (SIGPIPE signal).
  9679.  
  9680. value getsockname : file_descr -> sockaddr
  9681.  
  9682.     Return the address of the given socket.
  9683.  
  9684. value getpeername : file_descr -> sockaddr
  9685.  
  9686.     Return the address of the host connected to the given socket.
  9687.  
  9688. value recv : file_descr -> string -> int -> int -> msg_flag list -> int
  9689. value recvfrom :
  9690.         file_descr -> string -> int -> int -> msg_flag list -> int * sockaddr
  9691.  
  9692.     Receive data from an unconnected socket.
  9693.  
  9694.  
  9695. Chapter 16.   The unix library:  Unix system calls                         163
  9696.  
  9697.  
  9698. value send : file_descr -> string -> int -> int -> msg_flag list -> int
  9699. value sendto :
  9700.         file_descr -> string -> int -> int -> msg_flag list -> sockaddr -> int
  9701.  
  9702.     Send data over an unconnected socket.
  9703.  
  9704.  
  9705. High-level network connection functions
  9706.  
  9707. value open_connection : sockaddr -> in_channel * out_channel
  9708.  
  9709.     Connect to a server at the given address.  Return a pair of buffered
  9710.     channels connected to the server.  Remember to call flush on the output
  9711.     channel at the right times to ensure correct synchronization.
  9712.  
  9713. value shutdown_connection : in_channel -> unit
  9714.  
  9715.     ``Shut down'' a connection established with open_connection; that is,
  9716.     transmit an end-of-file condition to the server reading on the other side
  9717.     of the connection.
  9718.  
  9719. value establish_server : (in_channel -> out_channel -> 'a) -> sockaddr -> unit
  9720.  
  9721.     Establish a server on the given address.  The function given as first
  9722.     argument is called for each connection with two buffered channels
  9723.     connected to the client.  A new process is created for each connection.
  9724.     The function establish_server never returns normally.
  9725.  
  9726.  
  9727. Host and protocol databases
  9728.  
  9729. type host_entry =
  9730.   { h_name : string;
  9731.     h_aliases : string vect;
  9732.     h_addrtype : socket_domain;
  9733.     h_addr_list : inet_addr vect }
  9734.  
  9735.     Structure of entries in the hosts database.
  9736.  
  9737. type protocol_entry =
  9738.   { p_name : string;
  9739.     p_aliases : string vect;
  9740.     p_proto : int }
  9741.  
  9742.     Structure of entries in the protocols database.
  9743.  
  9744. type service_entry =
  9745.   { s_name : string;
  9746.     s_aliases : string vect;
  9747.     s_port : int;
  9748.     s_proto : string }
  9749.  
  9750.     Structure of entries in the services database.
  9751.  
  9752. value gethostname : unit -> string
  9753.  
  9754.     Return the name of the local host.
  9755.  
  9756.  
  9757. Chapter 16.  The unix library: Unix system calls                           164
  9758.  
  9759.  
  9760. value gethostbyname : string -> host_entry
  9761.  
  9762.     Find an entry in hosts with the given name, or raise Not_found.
  9763.  
  9764. value gethostbyaddr : inet_addr -> host_entry
  9765.  
  9766.     Find an entry in hosts with the given address, or raise Not_found.
  9767.  
  9768. value getprotobyname : string -> protocol_entry
  9769.  
  9770.     Find an entry in protocols with the given name, or raise Not_found.
  9771.  
  9772. value getprotobynumber : int -> protocol_entry
  9773.  
  9774.     Find an entry in protocols with the given protocol number, or raise
  9775.     Not_found.
  9776.  
  9777. value getservbyname : string -> string -> service_entry
  9778.  
  9779.     Find an entry in services with the given name, or raise Not_found.
  9780.  
  9781. value getservbyport : int -> string -> service_entry
  9782.  
  9783.     Find an entry in services with the given service number, or raise
  9784.     Not_found.
  9785.  
  9786.  
  9787. Terminal interface
  9788.  
  9789.     The following functions implement the POSIX standard terminal interface.
  9790.     They provide control over asynchronous communication ports and
  9791.     pseudo-terminals.  Refer to the termios man page for a complete
  9792.     description.
  9793.  
  9794. type terminal_io = {
  9795.  
  9796.     Input modes:
  9797.  
  9798.     mutable c_ignbrk: bool;  (* Ignore the break condition. *)
  9799.     mutable c_brkint: bool;  (* Signal interrupt on break condition. *)
  9800.     mutable c_ignpar: bool;  (* Ignore characters with parity errors. *)
  9801.     mutable c_parmrk: bool;  (* Mark parity errors. *)
  9802.     mutable c_inpck: bool;   (* Enable parity check on input. *)
  9803.     mutable c_istrip: bool;  (* Strip 8th bit on input characters. *)
  9804.     mutable c_inlcr: bool;   (* Map NL to CR on input. *)
  9805.     mutable c_igncr: bool;   (* Ignore CR on input. *)
  9806.     mutable c_icrnl: bool;   (* Map CR to NL on input. *)
  9807.     mutable c_ixon: bool;    (* Recognize XON/XOFF characters on input. *)
  9808.     mutable c_ixoff: bool;   (* Emit XON/XOFF chars to control input flow. *)
  9809.  
  9810.     Output modes:
  9811.  
  9812.     mutable c_opost: bool;   (* Enable output processing. *)
  9813.     mutable c_olcuc: bool;   (* Map lowercase to uppercase on output. *)
  9814.     mutable c_onlcr: bool;   (* Map NL to CR/NL on output. *)
  9815.     mutable c_ocrnl: bool;   (* Map CR to NL on output. *)
  9816.     mutable c_onocr: bool;   (* No CR output at column 0. *)
  9817.     mutable c_onlret: bool;  (* NL is assumed to perform as CR. *)
  9818.  
  9819.  
  9820. Chapter 16.   The unix library:  Unix system calls                         165
  9821.  
  9822.  
  9823.     mutable c_ofill: bool;   (* Use fill characters instead of delays. *)
  9824.     mutable c_ofdel: bool;   (* Fill character is DEL instead of NULL. *)
  9825.     mutable c_nldly: int;    (* Newline delay type (0-1). *)
  9826.     mutable c_crdly: int;    (* Carriage return delay type (0-3). *)
  9827.     mutable c_tabdly: int;   (* Horizontal tab delay type (0-3). *)
  9828.     mutable c_bsdly: int;    (* Backspace delay type (0-1). *)
  9829.     mutable c_vtdly: int;    (* Vertical tab delay type (0-1). *)
  9830.     mutable c_ffdly: int;    (* Form feed delay type (0-1). *)
  9831.  
  9832.     Control modes:
  9833.  
  9834.     mutable c_obaud: int;    (* Output baud rate (0 means close connection).*)
  9835.     mutable c_ibaud: int;    (* Input baud rate. *)
  9836.     mutable c_csize: int;    (* Number of bits per character (5-8). *)
  9837.     mutable c_cstopb: int;   (* Number of stop bits (1-2). *)
  9838.     mutable c_cread: bool;   (* Reception is enabled. *)
  9839.     mutable c_parenb: bool;  (* Enable parity generation and detection. *)
  9840.     mutable c_parodd: bool;  (* Specify odd parity instead of even. *)
  9841.     mutable c_hupcl: bool;   (* Hang up on last close. *)
  9842.     mutable c_clocal: bool;  (* Ignore modem status lines. *)
  9843.  
  9844.     Local modes:
  9845.  
  9846.     mutable c_isig: bool;    (* Generate signal on INTR, QUIT, SUSP. *)
  9847.     mutable c_icanon: bool;  (* Enable canonical processing
  9848.                                 (line buffering and editing) *)
  9849.     mutable c_noflsh: bool;  (* Disable flush after INTR, QUIT, SUSP. *)
  9850.     mutable c_echo: bool;    (* Echo input characters. *)
  9851.     mutable c_echoe: bool;   (* Echo ERASE (to erase previous character). *)
  9852.     mutable c_echok: bool;   (* Echo KILL (to erase the current line). *)
  9853.     mutable c_echonl: bool;  (* Echo NL even if c_echo is not set. *)
  9854.  
  9855.     Control characters:
  9856.  
  9857.     mutable c_vintr: char;   (* Interrupt character (usually ctrl-C). *)
  9858.     mutable c_vquit: char;   (* Quit character (usually ctrl-\). *)
  9859.     mutable c_verase: char;  (* Erase character (usually DEL or ctrl-H). *)
  9860.     mutable c_vkill: char;   (* Kill line character (usually ctrl-U). *)
  9861.     mutable c_veof: char;    (* End-of-file character (usually ctrl-D). *)
  9862.     mutable c_veol: char;    (* Alternate end-of-line char. (usually none). *)
  9863.     mutable c_vmin: int;     (* Minimum number of characters to read
  9864.                                 before the read request is satisfied. *)
  9865.     mutable c_vtime: int;    (* Maximum read wait (in 0.1s units). *)
  9866.     mutable c_vstart: char;  (* Start character (usually ctrl-Q). *)
  9867.     mutable c_vstop: char    (* Stop character (usually ctrl-S). *)
  9868.   }
  9869. value tcgetattr: file_descr -> terminal_io
  9870.  
  9871.     Return the status of the terminal referred to by the given file
  9872.     descriptor.
  9873.  
  9874. type setattr_when = TCSANOW | TCSADRAIN | TCSAFLUSH
  9875. value tcsetattr: file_descr -> setattr_when -> terminal_io -> unit
  9876.  
  9877.     Set the status of the terminal referred to by the given file descriptor.
  9878.     The second argument indicates when the status change takes place:
  9879.     immediately (TCSANOW), when all pending output has been transmitted
  9880.     (TCSADRAIN), or after flushing all input that has been received but not
  9881.  
  9882.  
  9883. Chapter 16.   The unix library:  Unix system calls                         166
  9884.  
  9885.  
  9886.     read (TCSAFLUSH). TCSADRAIN is recommended when changing the output
  9887.     parameters; TCSAFLUSH, when changing the input parameters.
  9888.  
  9889. value tcsendbreak: file_descr -> int -> unit
  9890.  
  9891.     Send a break condition on the given file descriptor.  The second argument
  9892.     is the duration of the break, in 0.1s units; 0 means standard duration
  9893.     (0.25s).
  9894.  
  9895. value tcdrain: file_descr -> unit
  9896.  
  9897.     Waits until all output written on the given file descriptor has been
  9898.     transmitted.
  9899.  
  9900. type flush_queue = TCIFLUSH | TCOFLUSH | TCIOFLUSH
  9901. value tcflush: file_descr -> flush_queue -> unit
  9902.  
  9903.     Discard data written on the given file descriptor but not yet
  9904.     transmitted, or data received but not yet read, depending on the second
  9905.     argument:  TCIFLUSH flushes data received but not read, TCOFLUSH flushes
  9906.     data written but not transmitted, and TCIOFLUSH flushes both.
  9907.  
  9908. type flow_action = TCOOFF | TCOON | TCIOFF | TCION
  9909. value tcflow: file_descr -> flow_action -> unit
  9910.  
  9911.     Suspend or restart reception or transmission of data on the given file
  9912.     descriptor, depending on the second argument:  TCOOFF suspends output,
  9913.     TCOON restarts output, TCIOFF transmits a STOP character to suspend
  9914.     input, and TCION transmits a START character to restart input.
  9915.  
  9916.  
  9917.  
  9918.  
  9919.  
  9920.  
  9921.  
  9922.  
  9923.  
  9924.  
  9925.  
  9926. Chapter 17
  9927.  
  9928.  
  9929.  
  9930. The num library:  arbitrary-precision rational arithmetic
  9931.  
  9932.  
  9933.  
  9934. The num library (distributed in contrib/libnum) implements exact-precision
  9935. rational arithmetic.  It is built upon the state-of-the-art BigNum
  9936. arbitrary-precision integer arithmetic package, and therefore achieves very
  9937. high performance.
  9938.   The functions provided in this library are fully documented in The CAML
  9939. Numbers Reference Manual by Valerie Menissier-Morain, technical report 141,
  9940. INRIA, july 1992 (available by anonymous FTP from ftp.inria.fr, directory
  9941. INRIA/publications/RT, file RT-0141.ps.Z). A summary of the functions is given
  9942. below.
  9943.   Programs that use the num library must be linked in ``custom runtime'' mode,
  9944. as follows:
  9945.  
  9946.         camlc -custom other options nums.zo other files -lnums
  9947.  
  9948. For interactive use of the num library, run camllight camlnum.
  9949.  
  9950. Mac:  This library is not available.
  9951.  
  9952. PC:   This library is not available.
  9953.  
  9954.  
  9955. 17.1 num:  operations on numbers
  9956.  
  9957.     Numbers (type num) are arbitrary-precision rational numbers, plus the
  9958.     special elements 1/0 (infinity) and 0/0 (undefined).
  9959.  
  9960. type num = Int of int | Big_int of big_int | Ratio of ratio
  9961.  
  9962.     The type of numbers.
  9963.  
  9964.  
  9965. Arithmetic operations
  9966.  
  9967. value prefix +/ : num -> num -> num
  9968. value add_num : num -> num -> num
  9969.  
  9970.     Addition
  9971.  
  9972. value minus_num : num -> num
  9973.  
  9974.     Unary negation.
  9975.  
  9976. value prefix -/ : num -> num -> num
  9977.  
  9978.  
  9979.                                      167
  9980.  
  9981.  
  9982. Chapter 17.   The num library:  arbitrary-precision rational arithmetic    168
  9983.  
  9984.  
  9985. value sub_num : num -> num -> num
  9986.  
  9987.     Subtraction
  9988.  
  9989. value prefix */ : num -> num -> num
  9990. value mult_num : num -> num -> num
  9991.  
  9992.     Multiplication
  9993.  
  9994. value square_num : num -> num
  9995.  
  9996.     Squaring
  9997.  
  9998. value prefix // : num -> num -> num
  9999. value div_num : num -> num -> num
  10000.  
  10001.     Division
  10002.  
  10003. value quo_num : num -> num -> num
  10004. value mod_num : num -> num -> num
  10005.  
  10006.     Euclidean division:  quotient and remainder
  10007.  
  10008. value prefix **/ : num -> num -> num
  10009. value power_num : num -> num -> num
  10010.  
  10011.     Exponentiation
  10012.  
  10013. value is_integer_num : num -> bool
  10014.  
  10015.     Test if a number is an integer
  10016.  
  10017. value integer_num : num -> num
  10018. value floor_num : num -> num
  10019. value round_num : num -> num
  10020. value ceiling_num : num -> num
  10021.  
  10022.     Approximate a number by an integer.  floor_num n returns the largest
  10023.     integer smaller or equal to n.  ceiling_num n returns the smallest
  10024.     integer bigger or equal to n.  integer_num n returns the integer closest
  10025.     to n.  In case of ties, rounds towards zero.  round_num n returns the
  10026.     integer closest to n.  In case of ties, rounds off zero.
  10027.  
  10028. value sign_num : num -> int
  10029.  
  10030.     Return -1, 0 or 1 according to the sign of the argument.
  10031.  
  10032. value prefix =/ : num -> num -> bool
  10033. value prefix </ : num -> num -> bool
  10034. value prefix >/ : num -> num -> bool
  10035. value prefix <=/ : num -> num -> bool
  10036. value prefix >=/ : num -> num -> bool
  10037. value prefix <>/ : num -> num -> bool
  10038. value eq_num : num -> num -> bool
  10039. value lt_num : num -> num -> bool
  10040. value le_num : num -> num -> bool
  10041. value gt_num : num -> num -> bool
  10042. value ge_num : num -> num -> bool
  10043.  
  10044.  
  10045. Chapter 17.  The num library: arbitrary-precision rational arithmetic      169
  10046.  
  10047.  
  10048.     Usual comparisons between numbers
  10049.  
  10050. value compare_num : num -> num -> int
  10051.  
  10052.     Return -1, 0 or 1 if the first argument is less than, equal to, or
  10053.     greater than the second argument.
  10054.  
  10055. value max_num : num -> num -> num
  10056. value min_num : num -> num -> num
  10057.  
  10058.     Return the greater (resp.  the smaller) of the two arguments.
  10059.  
  10060. value abs_num : num -> num
  10061.  
  10062.     Absolute value.
  10063.  
  10064. value succ_num: num -> num
  10065.  
  10066.     succ n is n+1
  10067.  
  10068. value pred_num: num -> num
  10069.  
  10070.     pred n is n-1
  10071.  
  10072. value incr_num: num ref -> unit
  10073.  
  10074.     incr r is r:=!r+1, where r is a reference to a number.
  10075.  
  10076. value decr_num: num ref -> unit
  10077.  
  10078.     decr r is r:=!r-1, where r is a reference to a number.
  10079.  
  10080.  
  10081. Coercions with strings
  10082.  
  10083. value string_of_num : num -> string
  10084.  
  10085.     Convert a number to a string, using fractional notation.
  10086.  
  10087. value approx_num_fix : int -> num -> string
  10088. value approx_num_exp : int -> num -> string
  10089.  
  10090.     Approximate a number by a decimal.  The first argument is the required
  10091.     precision.  The second argument is the number to approximate.  approx_fix
  10092.     uses decimal notation; the first argument is the number of digits after
  10093.     the decimal point.  approx_exp uses scientific (exponential) notation;
  10094.     the first argument is the number of digits in the mantissa.
  10095.  
  10096. value num_of_string : string -> num
  10097.  
  10098.     Convert a string to a number.
  10099.  
  10100.  
  10101. Coercions between numerical types
  10102.  
  10103. value int_of_num : num -> int
  10104. value num_of_int : int -> num
  10105.  
  10106.  
  10107. Chapter 17.   The num library:  arbitrary-precision rational arithmetic    170
  10108.  
  10109.  
  10110. value nat_of_num : num -> nat
  10111. value num_of_nat : nat -> num
  10112. value num_of_big_int : big_int -> num
  10113. value big_int_of_num : num -> big_int
  10114. value ratio_of_num : num -> ratio
  10115. value num_of_ratio : ratio -> num
  10116. value float_of_num : num -> float
  10117.  
  10118.  
  10119. 17.2 arith_status:  flags that control rational arithmetic
  10120.  
  10121. value arith_status: unit -> unit
  10122.  
  10123.     Print the current status of the arithmetic flags.
  10124.  
  10125. value get_error_when_null_denominator : unit -> bool
  10126. value set_error_when_null_denominator : bool -> unit
  10127.  
  10128.     Get or set the flag null_denominator.  When on, attempting to create a
  10129.     rational with a null denominator raises an exception.  When off,
  10130.     rationals with null denominators are accepted.  Initially:  on.
  10131.  
  10132. value get_normalize_ratio : unit -> bool
  10133. value set_normalize_ratio : bool -> unit
  10134.  
  10135.     Get or set the flag normalize_ratio.  When on, rational numbers are
  10136.     normalized after each operation.  When off, rational numbers are not
  10137.     normalized until printed.  Initially:  off.
  10138.  
  10139. value get_normalize_ratio_when_printing : unit -> bool
  10140. value set_normalize_ratio_when_printing : bool -> unit
  10141.  
  10142.     Get or set the flag normalize_ratio_when_printing.  When on, rational
  10143.     numbers are normalized before being printed.  When off, rational numbers
  10144.     are printed as is, without normalization.  Initially:  on.
  10145.  
  10146. value get_approx_printing : unit -> bool
  10147. value set_approx_printing : bool -> unit
  10148.  
  10149.     Get or set the flag approx_printing.  When on, rational numbers are
  10150.     printed as a decimal approximation.  When off, rational numbers are
  10151.     printed as a fraction.  Initially:  off.
  10152.  
  10153. value get_floating_precision : unit -> int
  10154. value set_floating_precision : int -> unit
  10155.  
  10156.     Get or set the parameter floating_precision.  This parameter is the
  10157.     number of digits displayed when approx_printing is on.  Initially:  12.
  10158.  
  10159.  
  10160.  
  10161.  
  10162.  
  10163.  
  10164.  
  10165.  
  10166.  
  10167.  
  10168.  
  10169. Chapter 18
  10170.  
  10171.  
  10172.  
  10173. The str library:  regular expressions and string processing
  10174.  
  10175.  
  10176.  
  10177. The str library (distributed in contrib/libstr) provides high-level string
  10178. processing functions, some based on regular expressions.  It is intended to
  10179. support the kind of file processing that is usually performed with scripting
  10180. languages such as awk, perl or sed.
  10181.   Programs that use the str library must be linked in ``custom runtime'' mode,
  10182. as follows:
  10183.  
  10184.         camlc -custom other options str.zo other files -lstr
  10185.  
  10186. For interactive use of the str library, run camllight camlstr.
  10187.  
  10188. Mac:  This library is not available.
  10189.  
  10190. PC:   This library is not available.
  10191.  
  10192.  
  10193. 18.1 str:  regular expressions and high-level string processing
  10194.  
  10195. Regular expressions
  10196.  
  10197. type regexp
  10198.  
  10199.     The type of compiled regular expressions.
  10200.  
  10201. value regexp: string -> regexp
  10202.  
  10203.     Compile a regular expression.  The syntax for regular expressions is the
  10204.     same as in Gnu Emacs.  The special characters are $^.*+?[]\.  The
  10205.     following constructs are recognized:
  10206.     .      matches any character except newline
  10207.     *      (postfix) matches the previous expression zero, one or several
  10208.     times
  10209.     +      (postfix) matches the previous expression one or several times
  10210.     ?      (postfix) matches the previous expression once or not at all
  10211.     [..]   character set; ranges are denoted with -, as in a-z; an initial ^,
  10212.     as in ^0-9, complements the set
  10213.     ^      matches at beginning of line
  10214.     $      matches at end of line
  10215.     \|     (infix) alternative between two expressions
  10216.     \(..\) grouping and naming of the enclosed expression
  10217.     \1     the text matched by the first \(...\) expression (\2 for the
  10218.     second expression, etc)
  10219.     \b     matches word boundaries
  10220.  
  10221.  
  10222.                                      171
  10223.  
  10224.  
  10225. Chapter 18.   The str library:  regular expressions and string processing  172
  10226.  
  10227.  
  10228.     \      quotes special characters.
  10229.  
  10230. value regexp_case_fold: string -> regexp
  10231.  
  10232.     Same as regexp, but the compiled expression will match text in a
  10233.     case-insensitive way:  uppercase and lowercase letters will be considered
  10234.     equivalent.
  10235.  
  10236.  
  10237. String matching and searching
  10238.  
  10239. value string_match: regexp -> string -> int -> bool
  10240.  
  10241.     string_match r s start tests whether the characters in s starting at
  10242.     position start match the regular expression r.  The first character of a
  10243.     string has position 0, as usual.
  10244.  
  10245. value search_forward: regexp -> string -> int -> int
  10246.  
  10247.     search_forward r s start searchs the string s for a substring matching
  10248.     the regular expression r.  The search starts at position start and
  10249.     proceeds towards the end of the string.  Return the position of the first
  10250.     character of the matched substring, or raise Not_found if no substring
  10251.     matches.
  10252.  
  10253. value search_backward: regexp -> string -> int -> int
  10254.  
  10255.     Same as search_forward, but the search proceeds towards the beginning of
  10256.     the string.
  10257.  
  10258. value matched_string: string -> string
  10259.  
  10260.     matched_string s returns the substring of s that was matched by the
  10261.     latest string_match, search_forward or search_backward.  The user must
  10262.     make sure that the parameter s is the same string that was passed to the
  10263.     matching or searching function.
  10264.  
  10265. value match_beginning: unit -> int
  10266. value match_end: unit -> int
  10267.  
  10268.     match_beginning() returns the position of the first character of the
  10269.     substring that was matched by string_match, search_forward or
  10270.     search_backward.  match_end() returns the position of the character
  10271.     following the last character of the matched substring.
  10272.  
  10273. value matched_group: int -> string -> string
  10274.  
  10275.     matched_group n s returns the substring of s that was matched by the nth
  10276.     group \(...\) of the regular expression during the latest string_match,
  10277.     search_forward or search_backward.  The user must make sure that the
  10278.     parameter s is the same string that was passed to the matching or
  10279.     searching function.
  10280.  
  10281. value group_beginning: int -> int
  10282. value group_end: int -> int
  10283.  
  10284.     group_beginning n returns the position of the first character of the
  10285.     substring that was matched by the nth group of the regular expression.
  10286.  
  10287.  
  10288. Chapter 18.   The str library:  regular expressions and string processing  173
  10289.  
  10290.  
  10291.     group_end n returns the position of the character following the last
  10292.     character of the matched substring.
  10293.  
  10294.  
  10295. Replacement
  10296.  
  10297. value global_replace: regexp -> string -> string -> string
  10298.  
  10299.     global_replace regexp repl s returns a string identical to s, except that
  10300.     all substrings of s that match regexp have been replaced by repl.  The
  10301.     replacement text repl can contain \1, \2, etc; these sequences will be
  10302.     replaced by the text matched by the corresponding group in the regular
  10303.     expression.  \0 stands for the text matched by the whole regular
  10304.     expression.
  10305.  
  10306. value replace_first: regexp -> string -> string -> string
  10307.  
  10308.     Same as global_replace, except that only the first substring matching the
  10309.     regular expression is replaced.
  10310.  
  10311. value global_substitute: regexp -> (string -> string) -> string -> string
  10312.  
  10313.     global_substitute regexp subst s returns a string identical to s, except
  10314.     that all substrings of s that match regexp have been replaced by the
  10315.     result of function subst.  The function subst is called once for each
  10316.     matching substring, and receives s (the whole text) as argument.
  10317.  
  10318. value substitute_first: regexp -> (string -> string) -> string -> string
  10319.  
  10320.     Same as global_substitute, except that only the first substring matching
  10321.     the regular expression is replaced.
  10322.  
  10323.  
  10324. Splitting
  10325.  
  10326. value split: regexp -> string -> string list
  10327.  
  10328.     split r s splits s into substrings, taking as delimiters the substrings
  10329.     that match r, and returns the list of substrings.  For instance,
  10330.     split (regexp "[ \t]+") s splits s into blank-separated words.
  10331.  
  10332. value bounded_split: regexp -> string -> int -> string list
  10333.  
  10334.     Same as split, but splits into at most n substrings, where n is the extra
  10335.     integer parameter.
  10336.  
  10337.  
  10338. Joining
  10339.  
  10340. value concat: string list -> string
  10341.  
  10342.     Catenate a list of string.
  10343.  
  10344. value join: string -> string list -> string
  10345.  
  10346.     Catenate a list of string.  The first argument is a separator, which is
  10347.     inserted between the strings.
  10348.  
  10349.  
  10350. Chapter 18.   The str library:  regular expressions and string processing  174
  10351.  
  10352.  
  10353. Extracting substrings
  10354.  
  10355. value string_before: string -> int -> string
  10356.  
  10357.     string_before s n returns the substring of all characters of s that
  10358.     precede position n (excluding the character at position n).
  10359.  
  10360. value string_after: string -> int -> string
  10361.  
  10362.     string_after s n returns the substring of all characters of s that follow
  10363.     position n (including the character at position n).
  10364.  
  10365. value first_chars: string -> int -> string
  10366.  
  10367.     first_chars s n returns the first n characters of s.  This is the same
  10368.     function as string_before.
  10369.  
  10370. value last_chars: string -> int -> string
  10371.  
  10372.     last_chars s n returns the last n characters of s.
  10373.  
  10374.  
  10375. Formatting
  10376.  
  10377. value format: ('a, unit, string) printf__format -> 'a
  10378.  
  10379.     Same as fprintf and printf from the printf module, except that the result
  10380.     of the formatting is returned as a string instead of being written on a
  10381.     channel.  The structure of the format string is described in printf.
  10382.  
  10383.  
  10384.  
  10385.  
  10386.  
  10387.  
  10388.  
  10389.  
  10390.  
  10391.  
  10392.  
  10393.  
  10394.  
  10395.  
  10396.  
  10397.  
  10398.  
  10399.  
  10400.  
  10401.  
  10402.  
  10403.  
  10404.  
  10405.  
  10406.                                     Part V
  10407.  
  10408.  
  10409.  
  10410.                                    Appendix
  10411.  
  10412.  
  10413.  
  10414.  
  10415.  
  10416.  
  10417.  
  10418.  
  10419.  
  10420.  
  10421.  
  10422.  
  10423.  
  10424.  
  10425.  
  10426.  
  10427.  
  10428.  
  10429.  
  10430.  
  10431.  
  10432.  
  10433.  
  10434.  
  10435.  
  10436.  
  10437.  
  10438.  
  10439.  
  10440.  
  10441.  
  10442.  
  10443.  
  10444.  
  10445.  
  10446.  
  10447.                                      175
  10448.  
  10449.  
  10450.  
  10451.  
  10452.  
  10453.  
  10454.  
  10455.  
  10456.  
  10457.  
  10458.  
  10459. Chapter 19
  10460.  
  10461.  
  10462.  
  10463. Further reading
  10464.  
  10465.  
  10466.  
  10467. For the interested reader, we list below some references to books and reports
  10468. related (sometimes loosely) to Caml Light.
  10469.  
  10470.  
  10471. 19.1 Programming in ML
  10472.  
  10473. The books below are programming courses taught in ML. Their main goal is to
  10474. teach programming, not to describe ML in full details --- though most contain
  10475. fairly good introductions to the ML language.  Some of those books use the
  10476. Standard ML dialect instead of the Caml dialect, so you will have to keep in
  10477. mind the differences in syntax and in semantics.
  10478.  
  10479.  -  Pierre Weis and Xavier Leroy.  Le langage Caml.  InterEditions, 1993.
  10480.  
  10481.     The natural companion to this manual, provided you read French.  This
  10482.     book is a step-by-step introduction to programming in Caml, and presents
  10483.     many realistic examples of Caml programs.
  10484.  
  10485.  -  Guy Cousineau and Michel Mauny.  Approche fonctionnelle de la
  10486.     programmation.  Ediscience, 1995.
  10487.  
  10488.     Another Caml programming course written in French, with many original
  10489.     examples.
  10490.  
  10491.  -  Lawrence C. Paulson.  ML for the working programmer.  Cambridge
  10492.     University Press, 1991.
  10493.  
  10494.     A good introduction to programming in Standard ML. Develops a theorem
  10495.     prover as a complete example.  Contains a presentation of the module
  10496.     system of Standard ML.
  10497.  
  10498.  -  Jeffrey D. Ullman.  Elements of ML programming.  Prentice Hall, 1993.
  10499.  
  10500.     Another good introduction to programming in Standard ML. No realistic
  10501.     examples, but a very detailed presentation of the language constructs.
  10502.  
  10503.  -  Ryan Stansifer.  ML primer.  Prentice-Hall, 1992.
  10504.  
  10505.     A short, but nice introduction to programming in Standard ML.
  10506.  
  10507.  -  Therese Accart Hardin and Veronique Donzeau-Gouge Viguie.  Concepts et
  10508.     outils de la programmation.  Du fonctionnel a l'imperatif avec Caml et
  10509.     Ada.  InterEditions, 1992.
  10510.  
  10511.  
  10512.                                      176
  10513.  
  10514.  
  10515. Chapter 19.   Further reading                                              177
  10516.  
  10517.  
  10518.     A first course in programming, that first introduces the main programming
  10519.     notions in Caml, then shows them underlying Ada.  Intended for beginners;
  10520.     slow-paced for the others.
  10521.  
  10522.  -  Rachel Harrison.  Abstract Data Types in Standard ML. John Wiley & Sons,
  10523.     1993.
  10524.  
  10525.     A presentation of Standard ML from the standpoint of abstract data types.
  10526.     Uses intensively the Standard ML module system.
  10527.  
  10528.  -  Harold Abelson and Gerald Jay Sussman.  Structure and Interpretation of
  10529.     Computer Programs.  The MIT press, 1985.  (French translation:  Structure
  10530.     et interpretation des programmes informatiques, InterEditions, 1989.)
  10531.  
  10532.     An outstanding course on programming, taught in Scheme, the modern
  10533.     dialect of Lisp.  Well worth reading, even if you are more interested in
  10534.     ML than in Lisp.
  10535.  
  10536.  
  10537. 19.2 Descriptions of ML dialects
  10538.  
  10539. The books and reports below are descriptions of various programming languages
  10540. from the ML family.  They assume some familiarity with ML.
  10541.  
  10542.  -  Xavier Leroy and Pierre Weis.  Manuel de reference du langage Caml.
  10543.     InterEditions, 1993.
  10544.  
  10545.     The French edition of the present reference manual and user's manual.
  10546.  
  10547.  -  Robert Harper.  Introduction to Standard ML. Technical report
  10548.     ECS-LFCS-86-14, University of Edinburgh, 1986.
  10549.  
  10550.     An overview of Standard ML, including the module system.  Terse, but
  10551.     still readable.
  10552.  
  10553.  -  Robin Milner, Mads Tofte and Robert Harper.  The definition of Standard
  10554.     ML. The MIT press, 1990.
  10555.  
  10556.     A complete formal definition of Standard ML, in the framework of
  10557.     structured operational semantics.  This book is probably the most
  10558.     mathematically precise definition of a programming language ever written.
  10559.     It is heavy on formalism and extremely terse, so even readers who are
  10560.     thoroughly familiar with ML will have major difficulties with it.
  10561.  
  10562.  -  Robin Milner and Mads Tofte.  Commentary on Standard ML. The MIT Press,
  10563.     1991.
  10564.  
  10565.     A commentary on the book above, that attempts to explain the most
  10566.     delicate parts and motivate the design choices.  Easier to read than the
  10567.     Definition, but still rather involving.
  10568.  
  10569.  -  Guy Cousineau and Gerard Huet.  The CAML primer.  Technical report 122,
  10570.     INRIA, 1990.
  10571.  
  10572.     A short description of the original Caml system, from which Caml Light
  10573.     has evolved.  Some familiarity with Lisp is assumed.
  10574.  
  10575.  
  10576. Chapter 19.   Further reading                                              178
  10577.  
  10578.  
  10579.  -  Pierre Weis et al.  The CAML reference manual, version 2.6.1.  Technical
  10580.     report 121, INRIA, 1990.
  10581.  
  10582.     The manual for the original Caml system, from which Caml Light has
  10583.     evolved.
  10584.  
  10585.  -  Michael J. Gordon, Arthur J. Milner and Christopher P. Wadsworth.
  10586.     Edinburgh LCF. Lecture Notes in Computer Science volume 78,
  10587.     Springer-Verlag, 1979.
  10588.  
  10589.     This is the first published description of the ML language, at the time
  10590.     when it was nothing more than the control language for the LCF system, a
  10591.     theorem prover.  This book is now obsolete, since the ML language has
  10592.     much evolved since then; but it is still of historical interest.
  10593.  
  10594.  -  Paul Hudak, Simon Peyton-Jones and Philip Wadler.  Report on the
  10595.     programming language Haskell, version 1.1.  Technical report, Yale
  10596.     University, 1991.
  10597.  
  10598.     Haskell is a purely functional language with lazy semantics that shares
  10599.     many important points with ML (full functionality, polymorphic typing),
  10600.     but has interesting features of its own (dynamic overloading, also called
  10601.     type classes).
  10602.  
  10603.  
  10604. 19.3 Implementing functional programming languages
  10605.  
  10606. The references below are intended for those who are curious to learn how a
  10607. language like Caml Light is compiled and implemented.
  10608.  
  10609.  -  Xavier Leroy.  The ZINC experiment:  an economical implementation of the
  10610.     ML language.  Technical report 117, INRIA, 1990.  (Available by anonymous
  10611.     FTP on ftp.inria.fr.)
  10612.  
  10613.     A description of the ZINC implementation, the prototype ML implementation
  10614.     that has evolved into Caml Light.  Large parts of this report still apply
  10615.     to the current Caml Light system, in particular the description of the
  10616.     execution model and abstract machine.  Other parts are now obsolete.  Yet
  10617.     this report still gives a complete overview of the implementation
  10618.     techniques used in Caml Light.
  10619.  
  10620.  -  Simon Peyton-Jones.  The implementation of functional programming
  10621.     languages.  Prentice-Hall, 1987.  (French translation:  Mise en  uvre des
  10622.     langages fonctionnels de programmation, Masson, 1990.)
  10623.  
  10624.     An excellent description of the implementation of purely functional
  10625.     languages with lazy semantics, using the technique known as graph
  10626.     reduction.  The part of the book that deals with the transformation from
  10627.     ML to enriched lambda-calculus directly applies to Caml Light.  You will
  10628.     find a good description of how pattern-matching is compiled and how types
  10629.     are inferred.  The remainder of the book does not apply directly to Caml
  10630.     Light, since Caml Light is not purely functional (it has side-effects),
  10631.     has strict semantics, and does not use graph reduction at all.
  10632.  
  10633.  -  Andrew W. Appel.  Compiling with continuations.  Cambridge University
  10634.     Press, 1992.
  10635.  
  10636.  
  10637. Chapter 19.   Further reading                                              179
  10638.  
  10639.  
  10640.     A complete description of an optimizing compiler for Standard ML, based
  10641.     on an intermediate representation called continuation-passing style.
  10642.     Shows how many advanced program optimizations can be applied to ML. Not
  10643.     directly relevant to the Caml Light system, since Caml Light does not use
  10644.     continuation-passing style at all, and makes little attempts at
  10645.     optimizing programs.
  10646.  
  10647.  
  10648. 19.4 Applications of ML
  10649.  
  10650. The following reports show ML at work in various, sometimes unexpected, areas.
  10651.  
  10652.  -  Emmanuel Chailloux and Guy Cousineau.  The MLgraph primer.  Technical
  10653.     report 92-15, Ecole Normale Superieure, 1992.  (Available by anonymous
  10654.     FTP on ftp.ens.fr.)
  10655.  
  10656.     Describes a Caml Light library that produces Postscript pictures through
  10657.     high-level drawing functions.
  10658.  
  10659.  -  Xavier Leroy.  Programmation du systeme Unix en Caml Light.  Technical
  10660.     report 147, INRIA, 1992.  (Available by anonymous FTP on ftp.inria.fr.)
  10661.  
  10662.     A Unix systems programming course, demonstrating the use of the Caml
  10663.     Light library that gives access to Unix system calls.
  10664.  
  10665.  -  John H. Reppy.  Concurrent programming with events --- The concurrent ML
  10666.     manual.  Cornell University, 1990.  (Available by anonymous FTP on
  10667.     research.att.com.)
  10668.  
  10669.     Concurrent ML extends Standard ML of New Jersey with concurrent processes
  10670.     that communicate through channels and events.
  10671.  
  10672.  -  Jeannette M. Wing, Manuel Faehndrich, J. Gregory Morrisett and Scottt
  10673.     Nettles.  Extensions to Standard ML to support transactions.  Technical
  10674.     report CMU-CS-92-132, Carnegie-Mellon University, 1992.  (Available by
  10675.     anonymous FTP on reports.adm.cs.cmu.edu.)
  10676.  
  10677.     How to integrate the basic database operations to Standard ML.
  10678.  
  10679.  -  Emden R. Gansner and John H. Reppy.  eXene.  Bell Labs, 1991.  (Available
  10680.     by anonymous FTP on research.att.com.)
  10681.  
  10682.     An interface between Standard ML of New Jersey and the X Windows
  10683.     windowing system.
  10684.  
  10685.  
  10686.  
  10687.  
  10688.  
  10689.  
  10690.  
  10691.  
  10692.  
  10693. Index to the library
  10694.  
  10695.  
  10696.  
  10697. ! (infix), 113                           approx_num_exp, 169
  10698. != (infix), 100                          approx_num_fix, 169
  10699. * (infix), 101, 103                      arg (module), 119
  10700. ** (infix), 101                          arith_status, 170
  10701. **. (infix), 101                         arith_status (module), 170
  10702. **/ (infix), 168                         asin, 102
  10703. *. (infix), 101                          asr (infix), 104
  10704. */ (infix), 168                          assoc, 112
  10705. + (infix), 101, 103                      assq, 112
  10706. +. (infix), 101                          atan, 102
  10707. +/ (infix), 167                          atan2, 102
  10708. - (infix), 101, 103                      background, 144
  10709. -. (infix), 101                          Bad (exception), 120
  10710. -/ (infix), 168                          baltree (module), 120
  10711. / (infix), 101, 103                      basename, 122
  10712. /. (infix), 101                          big_int_of_num, 170
  10713. // (infix), 168                          bind, 162
  10714. < (infix), 99                            black, 143
  10715. <. (infix), 102                          blit_image, 146
  10716. </ (infix), 169                          blit_string, 115
  10717. <= (infix), 99                           blit_vect, 117
  10718. <=. (infix), 102                         blue, 143
  10719. <=/ (infix), 169                         bool (module), 97
  10720. <> (infix), 99                           bounded_split, 173
  10721. <>. (infix), 101                         Break (exception), 139
  10722. <>/ (infix), 169                         builtin (module), 98
  10723. = (infix), 99                            button_down, 147
  10724. =. (infix), 101
  10725. =/ (infix), 169                          catch_break, 139
  10726. == (infix), 99                           cd, 53
  10727. > (infix), 99                            ceiling_num, 168
  10728. >. (infix), 102                          char (module), 98
  10729. >/ (infix), 169                          char_for_read, 99
  10730. >= (infix), 99                           char_of_int, 99
  10731. >=. (infix), 102                         chdir, 139, 155
  10732. >=/ (infix), 169                         check_suffix, 122
  10733. @ (infix), 110                           chmod, 154
  10734. ^ (infix), 115                           choose, 137
  10735. abs, 104                                 chop_suffix, 122
  10736. abs_float, 102                           chown, 154
  10737. abs_num, 169                             clear, 129, 135, 137
  10738. accept, 162                              clear_graph, 143
  10739. access, 155                              clear_parser, 132
  10740. acos, 102                                close, 139, 152
  10741. add, 120, 129, 132, 134, 136             close_box, 123
  10742. add_float, 101                           close_graph, 143
  10743. add_int, 103                             close_in, 110
  10744. add_num, 167                             close_out, 108
  10745. alarm, 159                               close_process, 156
  10746.  
  10747.  
  10748.                                      180
  10749.  
  10750.  
  10751. Index to the library                                                       181
  10752.  
  10753.  
  10754. close_process_in, 156                    end_of_stream, 114
  10755. close_process_out, 156                   environment, 150
  10756. close_tbox, 124                          eprint, 134
  10757. closedir, 156                            eprintf, 134
  10758. combine, 113                             eq (module), 99
  10759. command_line, 138                        eq_float, 101
  10760. compare, 99, 121, 136                    eq_int, 103
  10761. compare_num, 169                         eq_num, 169
  10762. compare_strings, 116                     eq_string, 116
  10763. compile, 51                              equal, 136
  10764. concat, 121, 173                         error_message, 150
  10765. concat_vect, 117                         establish_server, 163
  10766. connect, 162                             exc (module), 100
  10767. contains, 120                            except, 112
  10768. copy_vect, 117                           exceptq, 112
  10769. cos, 102                                 execv, 150
  10770. create_image, 146                        execve, 150
  10771. create_lexer, 131                        execvp, 151
  10772. create_lexer_channel, 130                exists, 111
  10773. create_lexer_string, 130                 exit, 105, 139
  10774. create_string, 115                       Exit (exception), 100
  10775. current_dir_name, 121                    exp, 102
  10776. current_point, 144                       Failure (exception), 100
  10777. cyan, 143                                failwith, 100
  10778. debug_mode, 52                           fchar (module), 100
  10779. decr, 113                                fchmod, 154
  10780. decr_num, 169                            fchown, 154
  10781. descr_of_in_channel, 152                 fcntl_int, 155
  10782. descr_of_out_channel, 153                fcntl_ptr, 155
  10783. diff, 136                                filename (module), 121
  10784. directory, 53                            fill_arc, 145
  10785. dirname, 122                             fill_circle, 145
  10786. div_float, 101                           fill_ellipse, 145
  10787. div_int, 103                             fill_poly, 145
  10788. div_num, 168                             fill_rect, 145
  10789. Division_by_zero (exception), 103        fill_string, 115
  10790. do_list, 111                             fill_vect, 117
  10791. do_list2, 111                            find, 121, 129, 132
  10792. do_list_combine, 113                     find_all, 129
  10793. do_stream, 114                           first_chars, 174
  10794. do_table, 129                            flat_map, 111
  10795. do_table_rev, 130                        float, 135
  10796. do_vect, 118                             float (module), 101
  10797. draw_arc, 144                            float_of_int, 101
  10798. draw_char, 145                           float_of_num, 170
  10799. draw_circle, 144                         float_of_string, 102
  10800. draw_ellipse, 144                        floor_num, 168
  10801. draw_image, 146                          flush, 107
  10802. draw_string, 145                         fold, 137
  10803. dump_image, 146                          for_all, 111
  10804. dup, 156                                 force_newline, 124
  10805. dup2, 156                                foreground, 144
  10806. elements, 136                            fork, 151
  10807. empty, 132, 136                          format, 174
  10808. Empty (exception), 134, 137              format (module), 122
  10809. End_of_file (exception), 105             fprint, 134
  10810.                                          fprintf, 133
  10811.  
  10812.  
  10813. Index to the library                                                       182
  10814.  
  10815.  
  10816. fst, 112                                 graphics (module), 142
  10817. fstat, 154                               green, 143
  10818. fstring (module), 102                    group_beginning, 172
  10819. ftruncate, 153                           group_end, 172
  10820. full_init, 135                           gt_float, 102
  10821. full_major, 128                          gt_int, 104
  10822. fvect (module), 102                      gt_num, 169
  10823. gc (module), 126                         gt_string, 116
  10824. ge_float, 102                            handle_unix_error, 150
  10825. ge_int, 104                              hash, 130
  10826. ge_num, 169                              hash_param, 130
  10827. ge_string, 116                           hashtbl (module), 129
  10828. genlex (module), 128                     hd, 110
  10829. get, 127                                 in_channel_length, 110
  10830. get_approx_printing, 170                 in_channel_of_descr, 152
  10831. get_ellipsis_text, 126                   include, 51
  10832. get_error_when_null_denominator, 170     incr, 113
  10833. get_floating_precision, 170              incr_num, 169
  10834. get_formatter_output_functions, 126      index, 112
  10835. get_image, 146                           inet_addr_of_string, 161
  10836. get_lexeme, 131                          init, 135
  10837. get_lexeme_char, 131                     input, 109
  10838. get_lexeme_end, 131                      input_binary_int, 109
  10839. get_lexeme_start, 131                    input_byte, 109
  10840. get_margin, 125                          input_char, 109
  10841. get_max_boxes, 125                       input_line, 109
  10842. get_max_indent, 125                      input_value, 109
  10843. get_normalize_ratio, 170                 install_printer, 52
  10844. get_normalize_ratio_when_printing,       int, 135
  10845.       170                                int (module), 103
  10846. getcwd, 155                              int_of_char, 98
  10847. getegid, 160                             int_of_float, 101
  10848. getenv, 139                              int_of_num, 170
  10849. geteuid, 160                             int_of_string, 104
  10850. getgid, 160                              integer_num, 168
  10851. getgrgid, 161                            inter, 136
  10852. getgrnam, 160                            interactive, 138
  10853. getgroups, 160                           intersect, 112
  10854. gethostbyaddr, 164                       invalid_arg, 100
  10855. gethostbyname, 164                       Invalid_argument (exception), 100
  10856. gethostname, 163                         io (module), 105
  10857. getlogin, 160                            ioctl_int, 157
  10858. getpeername, 162                         ioctl_ptr, 157
  10859. getpid, 151                              is_absolute, 122
  10860. getppid, 151                             is_empty, 136
  10861. getprotobyname, 164                      is_integer_num, 168
  10862. getprotobynumber, 164                    it_list, 111
  10863. getpwnam, 160                            it_list2, 111
  10864. getpwuid, 161                            iter, 132, 135, 136, 138
  10865. getservbyname, 164
  10866. getservbyport, 164                       join, 173
  10867. getsockname, 162
  10868. getuid, 159                              key_pressed, 147
  10869. global_replace, 173                      kill, 158
  10870. global_substitute, 173
  10871. gmtime, 159                              land (infix), 104
  10872. Graphic_failure (exception), 142         last_chars, 174
  10873.  
  10874.  
  10875. Index to the library                                                       183
  10876.  
  10877.  
  10878. le_float, 102                            min, 99
  10879. le_int, 104                              min_num, 169
  10880. le_num, 169                              minor, 128
  10881. le_string, 116                           minus, 101, 103
  10882. length, 135, 138                         minus_float, 101
  10883. lexing (module), 130                     minus_int, 103
  10884. lineto, 144                              minus_num, 167
  10885. link, 154                                mkdir, 155
  10886. list (module), 110                       mkfifo, 156
  10887. list_it, 111                             mod (infix), 103
  10888. list_it2, 111                            mod_num, 168
  10889. list_length, 110                         modify, 121
  10890. list_of_vect, 117                        mouse_pos, 147
  10891. listen, 162                              moveto, 144
  10892. lnot, 104                                mult_float, 101
  10893. load, 51                                 mult_int, 103
  10894. load_object, 51                          mult_num, 168
  10895. localtime, 159                           nat_of_num, 170
  10896. lockf, 157                               neq_float, 101
  10897. log, 102                                 neq_int, 103
  10898. lor (infix), 104                         neq_string, 116
  10899. lseek, 153                               new, 129, 134, 137
  10900. lshift_left, 104                         nice, 151
  10901. lshift_right, 104                        not (infix), 98
  10902. lsl (infix), 104                         Not_found (exception), 100
  10903. lsr (infix), 104                         nth_char, 115
  10904. lstat, 154                               num (module), 167
  10905. lt_float, 102                            num_of_big_int, 170
  10906. lt_int, 104                              num_of_int, 170
  10907. lt_num, 169                              num_of_nat, 170
  10908. lt_string, 116                           num_of_ratio, 170
  10909. lxor (infix), 104                        num_of_string, 169
  10910. magenta, 143                             open, 139, 152
  10911. major, 128                               open_connection, 163
  10912. make_image, 146                          open_descriptor_in, 109
  10913. make_lexer, 128                          open_descriptor_out, 107
  10914. make_matrix, 117                         open_graph, 143
  10915. make_string, 115                         open_hbox, 122
  10916. make_vect, 116                           open_hovbox, 123
  10917. map, 110                                 open_hvbox, 123
  10918. map (module), 131                        open_in, 108
  10919. map2, 111                                open_in_bin, 108
  10920. map_combine, 113                         open_in_gen, 109
  10921. map_vect, 117                            open_out, 107
  10922. map_vect_list, 118                       open_out_bin, 107
  10923. match_beginning, 172                     open_out_gen, 107
  10924. match_end, 172                           open_process, 156
  10925. Match_failure (exception), 24, 26,       open_process_in, 156
  10926.       98                                 open_process_out, 156
  10927. matched_group, 172                       open_tbox, 124
  10928. matched_string, 172                      open_vbox, 122
  10929. max, 99                                  opendir, 155
  10930. max_num, 169                             out_channel_length, 108
  10931. mem, 111, 136                            out_channel_of_descr, 152
  10932. mem_assoc, 112                           Out_of_memory (exception), 100
  10933. memq, 112                                output, 107
  10934. merge, 137
  10935.  
  10936.  
  10937. Index to the library                                                       184
  10938.  
  10939.  
  10940. output_binary_int, 108                   ratio_of_num, 170
  10941. output_byte, 107                         read, 152
  10942. output_char, 107                         read_float, 106
  10943. output_compact_value, 108                read_int, 106
  10944. output_string, 107                       read_key, 147
  10945. output_value, 108                        read_line, 106
  10946. pair (module), 112                       readdir, 155
  10947. parse, 120                               readlink, 156
  10948. Parse_error (exception), 114, 133        really_input, 109
  10949. Parse_failure (exception), 114           recv, 162
  10950. parsing (module), 132                    recvfrom, 162
  10951. pause, 158                               red, 143
  10952. peek, 135                                ref (module), 113
  10953. pipe, 156                                regexp, 171
  10954. plot, 144                                regexp_case_fold, 172
  10955. point_color, 144                         remove, 121, 129, 132, 136, 139
  10956. pop, 137                                 remove_printer, 52
  10957. pos_in, 110                              rename, 139, 154
  10958. pos_out, 108                             replace_first, 173
  10959. power, 101                               replace_string, 116
  10960. power_num, 168                           rev, 110
  10961. pred, 103                                rewinddir, 155
  10962. pred_num, 169                            rgb, 143
  10963. prerr_char, 106                          rhs_end, 132
  10964. prerr_endline, 106                       rhs_start, 132
  10965. prerr_float, 106                         rmdir, 155
  10966. prerr_int, 106                           round_num, 168
  10967. prerr_string, 106                        s_irall, 138
  10968. print, 134                               s_irgrp, 138
  10969. print_as, 123                            s_iroth, 138
  10970. print_bool, 123                          s_irusr, 138
  10971. print_break, 123                         s_isgid, 138
  10972. print_char, 105, 123                     s_isuid, 138
  10973. print_cut, 124                           s_iwall, 138
  10974. print_endline, 106                       s_iwgrp, 138
  10975. print_float, 105, 123                    s_iwoth, 138
  10976. print_flush, 124                         s_iwusr, 138
  10977. print_if_newline, 124                    s_ixall, 138
  10978. print_int, 105, 123                      s_ixgrp, 138
  10979. print_newline, 106, 124                  s_ixoth, 138
  10980. print_space, 124                         s_ixusr, 138
  10981. print_stat, 127                          search_backward, 172
  10982. print_string, 105, 123                   search_forward, 172
  10983. print_tab, 125                           seek_in, 110
  10984. print_tbreak, 124                        seek_out, 108
  10985. printexc (module), 133                   select, 157
  10986. printf, 134                              send, 163
  10987. printf (module), 133                     sendto, 163
  10988. push, 137                                set, 127
  10989. queue (module), 134                      set (module), 135
  10990. quit, 51                                 set_approx_printing, 170
  10991. quo (infix), 103                         set_color, 143
  10992. quo_num, 168                             set_ellipsis_text, 125
  10993.                                          set_error_when_null_denominator, 170
  10994. raise, 100                               set_floating_precision, 170
  10995. random (module), 135                     set_font, 145
  10996.                                          set_formatter_output_channel, 126
  10997.  
  10998.  
  10999. Index to the library                                                       185
  11000.  
  11001.  
  11002. set_formatter_output_functions, 126      string_of_num, 169
  11003. set_line_width, 144                      sub_float, 101
  11004. set_margin, 125                          sub_int, 103
  11005. set_max_boxes, 125                       sub_num, 168
  11006. set_max_indent, 125                      sub_string, 115
  11007. set_normalize_ratio, 170                 sub_vect, 117
  11008. set_normalize_ratio_when_printing,       substitute_first, 173
  11009.       170                                subtract, 112
  11010. set_nth_char, 115                        succ, 103
  11011. set_print_depth, 52                      succ_num, 169
  11012. set_print_length, 52                     symbol_end, 132
  11013. set_tab, 125                             symbol_start, 132
  11014. set_text_size, 145                       symlink, 156
  11015. setgid, 160                              sys (module), 138
  11016. setuid, 160                              Sys_error (exception), 138
  11017. shutdown, 162                            system, 151
  11018. shutdown_connection, 163                 system_command, 139
  11019. sign_num, 168                            take, 135
  11020. signal, 158                              tan, 102
  11021. sin, 102                                 tcdrain, 166
  11022. size_x, 143                              tcflow, 166
  11023. size_y, 143                              tcflush, 166
  11024. sleep, 159                               tcgetattr, 165
  11025. snd, 113                                 tcsendbreak, 166
  11026. socket, 162                              tcsetattr, 165
  11027. socketpair, 162                          text_size, 145
  11028. sort, 137                                time, 159
  11029. sort (module), 137                       times, 159
  11030. sound, 147                               tl, 110
  11031. split, 113, 121, 173                     toplevel (module), 51
  11032. sqrt, 102                                trace, 52
  11033. square_num, 168                          transp, 146
  11034. stack (module), 137                      truncate, 153
  11035. stat, 127, 153
  11036. std_err, 105                             umask, 154
  11037. std_in, 105                              union, 112, 136
  11038. std_out, 105                             unix (module), 148
  11039. stderr, 105, 152                         Unix_error (exception), 150
  11040. stdin, 105, 152                          unlink, 154
  11041. stdout, 105, 152                         untrace, 52
  11042. str (module), 171                        utimes, 159
  11043. stream (module), 114
  11044. stream_check, 114                        vect (module), 116
  11045. stream_from, 114                         vect_assign, 116
  11046. stream_get, 114                          vect_item, 116
  11047. stream_next, 114                         vect_length, 116
  11048. stream_of_channel, 114                   vect_of_list, 117
  11049. stream_of_string, 114                    verbose_mode, 52
  11050. string (module), 115
  11051. string_after, 174                        wait, 151
  11052. string_before, 174                       wait_next_event, 147
  11053. string_for_read, 116                     waitopt, 151
  11054. string_length, 115                       waitpid, 151
  11055. string_match, 172                        white, 143
  11056. string_of_bool, 98                       write, 152
  11057. string_of_float, 102
  11058. string_of_inet_addr, 161                 yellow, 143
  11059. string_of_int, 104
  11060.  
  11061.  
  11062.  
  11063.  
  11064.  
  11065.  
  11066.  
  11067.  
  11068.  
  11069. Index of keywords
  11070.  
  11071.  
  11072.  
  11073. and, see let, type, exception,
  11074.       value, where
  11075. as, 20
  11076.  
  11077. begin, 22, 23
  11078.  
  11079. do, see while, for
  11080. done, see while, for
  11081. downto, see for
  11082.  
  11083. else, see if
  11084. end, 22, 23
  11085. exception, 31, 32
  11086.  
  11087. for, 22, 26
  11088. fun, 22
  11089. function, 22, 33
  11090.  
  11091. if, 22, 25
  11092. in, see let
  11093.  
  11094. let, 22, 24
  11095.  
  11096. match, 22, 25, 33
  11097. mutable, 30, 35
  11098.  
  11099. not, 22
  11100.  
  11101. of, see type, exception
  11102. or, 22, 26
  11103.  
  11104. prefix, 22, 28, 37
  11105.  
  11106. rec, see let, where
  11107.  
  11108. then, see if
  11109. to, see for
  11110. try, 22, 26
  11111. type, 30, 32
  11112.  
  11113. value, 32
  11114.  
  11115. when, 34
  11116. where, 35
  11117. while, 26
  11118. with, see match, try
  11119.  
  11120.  
  11121.  
  11122.  
  11123.  
  11124.  
  11125.  
  11126.  
  11127.                                      186
  11128.